使用jQuery禁用选择框选项并将边框变为红色

6

html

<select name="register-month" id="register-month">
    <option value="00">Month</option>
    <option value="01">January</option>
    <option value="02">February</option>
    <option value="03">March</option>
    <option value="04">April</option>
    <option value="05">May</option>
    <option value="06">June</option>
    <option value="07">July</option>
    <option value="08">August</option>
    <option value="09">September</option>
    <option value="10">October</option>
    <option value="11">November</option>
    <option value="12">December</option>
</select>

jquery

function checkbirthday() {
     var register_month_value = $("#register-month").val();
     //month check
     if (register_month_value === "") {
         $("#register-month option[value='00']").remove();
         $('#register-month').css('border-color', 'red');
     } else {
         $('#register-month').css('border-color', '#dfe0e6');
     }
     return;
 }

 $(document).ready(function() {
     $("#register-month").keyup(checkbirthday);
 });
我的意图很简单,首先我想要在点击选择器后禁用“月份”,其次,如果选择为空值,则将CSS边框更改为红色。但是我尝试了很多方法,仍然没有成功,这里出了什么问题?

1
该值永远不会是 "",因为当未选择月份时,您的 HTML 值设置为 00,如 <option value="00">Month</option>。因此,您只需要针对此进行检查。 - GillesC
http://jsfiddle.net/arunpjohny/bg122770/1/ - Arun P Johny
2个回答

5

请看内部评论:

// on change of the option selection
$('#register-month').on('change', function() {
    var selectedMonth = parseInt($(this).val(), 10); // Get value of selected option
    var borderColor;

    if (selectedMonth) { // If selected option is `Month`
        $(this).find('option[value="00"]').prop('disabled', true);
        borderColor = '#dfe0e6';
    } else {    
        borderColor = 'red';
    }

    $(this).css('border-color', borderColor); // Update the border colour of the dropdown.
});
演示: http://jsfiddle.net/tusharj/7w5ub8t9/

2
只需将其更改为
if(register_month_value === "00")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,