jquery on selection禁用选项并使边框变为红色

时间:2015-06-16 09:49:41

标签: javascript jquery html

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);
 });

我的意图很简单,1,我想在点击选择后禁用“月”,如果选择为空值,则为第2,将css边框更改为红色。

但我尝试了很多方法,但仍然没有运气,这里有什么问题?

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:2)

只需更改为

if(register_month_value === "00")