JQuery 检查多个选择值

JQuery check multiple Selects value

本文关键字:选择 检查 JQuery      更新时间:2023-09-26

我在一页上有许多HTML选择,如下所示:

<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 来涵盖所有内容。

您可以使用更改事件处理程序并检查所选值:
检查下面的代码段

 $('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>

看看这个: .val()

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

你必须自己迭代元素。幸运的是,它非常简单,并且对代码进行了非常小的更改:

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

如果您需要检查所有选择,则必须测试一个或多个是否为"未选择"。为此,您可以执行以下操作:

$(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>