2016-03-11 110 views
1

我已经选择了一些HTML的一个页面上类似如下:JQuery的检查多个选择价值

<div> 
<h3>Ethnicity</h3> 
<select> 
    <option value="select">Select</option> 
    <option value="african">African</option> 
    <option value="africanamerican">African American</option> 
    <option value="asian">Asian</option> 
</select> 
</div> 

我想使用jQuery来检查每一个选择,以保证初始值“中选择”已改变 - 例如: :已经选择了另一个选项。如果它没有改变,我想改变选择颜色。

我已经试过以下Jquery的,但它不是功能齐全:

if($('select').val() == 'select') { 
     alert('got one...'); 
     $(this).css({'color' : 'red'}); 
    } 

注:该页面有大约25选择,我试图让一块的jQuery覆盖所有。

+1

你看过了'VAL()'的文档?你明白为什么这不起作用吗? – Amit

+0

雅我可以看到它不起作用 - 试图现在使用.find(),然后在每个选择使用.val()。 – Adam

回答

1

看看这个:.val()

$("select").each(function(){ 
    if($(this).val() == "YourDefaulValue"){ 
     $(this).css({'color' : 'red'}); 
    } 
}); 
4

您可以使用更改事件处理程序,并检查选择的值:
检查片断下面

$('select').on('change', function() { 
 

 
    if ($(this).val() == 'select') { 
 
    alert('got one...'); 
 
    $(this).css({ 
 
     'color': 'red' 
 
    }); 
 
    } else { 
 
    $(this).css({ 
 
     'color': 'initial' 
 
    }); 
 
    } 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <h3>Ethnicity</h3> 
 
    <select> 
 
    <option value="select">Select</option> 
 
    <option value="african">African</option> 
 
    <option value="africanamerican">African American</option> 
 
    <option value="asian">Asian</option> 
 
    </select> 
 
</div>

1

你必须自己重复的元素。幸运的是,这是相当简单,一个非常小的改变了代码:

$('select').each(function() { 
    var $this = $(this); 
    if($this.val() == 'select') { 
    // probably shouldn't alert here... 
    // alert('got one...'); 
    $this.css({'color' : 'red'}); 
    } 
} 
1

如果您需要检查所有选择你要测试,如果一个或更多的是“未选择”。要做到这一点,你可以这样做:

$(function() { 
 
    $('#resetBtn').on('click', function(e) { 
 
    $('select').each(function(index, element) { 
 
     $(this).css({'color' : 'black'}); 
 
    }); 
 
    }); 
 
    $('#checkBtn').on('click', function(e) { 
 
    $('select').each(function(index, element) { 
 
     if (element.selectedIndex == 0) { 
 
     alert('got one...'); 
 
     $(this).css({'color' : 'red'}); 
 
     } 
 
    }); 
 
    }); 
 
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> 
 

 
<button id="checkBtn">Check select</button> 
 
<button id="resetBtn">Reset select</button> 
 
<div> 
 
    <h3>Ethnicity</h3> 
 
    <select> 
 
     <option value="select">Select</option> 
 
     <option value="african">African</option> 
 
     <option value="africanamerican">African American</option> 
 
     <option value="asian">Asian</option> 
 
    </select> 
 
</div>