0

I want to do something when a option selected contains a certain word, however the below does not work:

<select id="coloroption">
 <option value="172">Granite Gray</option>
 <option value="174">Hot Red</option>
 <option value="173">Navy</option>
 <option value="171">Kentucky Green</option>
</select>

$('#coloroption').change(function() {
var message_index = $(this).val();
if (message_index.indexOf('Kentucky') >= 0){
                alert('MINIMUM 12')}
});
4

3 回答 3

5

这是正确的工作代码:

 $('#coloroption').change(function(e) {
    var sel = $('#coloroption')[0];
    var message_index = sel.options[sel.selectedIndex].text;
    if (message_index.toLowerCase().indexOf('kentucky') >= 0){
            alert('MINIMUM 12')
    }
 });

只是打电话

 $('#coloroption').val()

实际上会给你选项的值,所以如果你想使用它,你必须比较'171'而不是文本值......

哦,这是jsFiddle 工作示例

于 2011-11-30T15:30:49.553 回答
3

你可以试试这个:

if (message_index.toLowerCase().indexOf('kentucky') >= 0){

JavaScript 字符串区分大小写,因此“Kentucky”不会匹配“kentucky”。

于 2011-11-30T15:20:35.300 回答
0

完整代码:)

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <select id="coloroption">
    <option>Granite Gray</option>
    <option>Hot Red</option>
    <option>Navy</option>
    <option>Kentucky Green</option>
  </select>
<script>

      $('#coloroption').change(function() {
          var str = "";
          $("select option:selected").each(function () {
              str += $(this).text();
          });

          if (str.toLowerCase().indexOf('kentucky') >= 0){
            alert('MINIMUM 12');
          }
        })
        .trigger('change');
</script>

</body>
</html>
于 2011-11-30T15:22:42.717 回答