开发者

jQuery how to select options by values?

How to select options which are not in 'restrictedIds', for example, selector should select the options with values 24 and 31. Also I know how it could be done with using 开发者_JS百科'.inArray' and '.each()' but it would be good to look at yours solutions. Thank you.

...
var restrictedIds='0,38,23';
...
<select class="text4" size="1" name="drivers">
        <option value="0"></option>
        <option value="24">test1</option>
        <option value="31">test2</option>
        <option value="38">test3</option>
        <option value="23">test4</option>
</select>


You should take a look at these articles:
http://api.jquery.com/attribute-equals-selector/
http://api.jquery.com/attribute-not-equal-selector/
http://api.jquery.com/multiple-attribute-selector/

What you can do is select only options from whitelist, i.e.

$('option[value=24],option[value=31]')

But I'm not sure if this is faster than .each()..


You can use .filter. For better performance I suggest to create a map of IDs:

var restrictedIds = {
    0: true,
    28: true,
    23: true
};

var options = $('select[name="drivers"] option').filter(function() {
    return !restrictedIds[this.value];
    //or   !(this.value in restrictedIds)
});


The simplest thing to do is use the val function http://api.jquery.com/val/. It has support to read and write values to select having multiple options.

Here is an example that may work for you.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; margin:4px; }
  b { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p></p>
  <select id="single">
    <option>Single</option>
    <option>Single2</option>

  </select>
  <select id="multiple" multiple="multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
  </select>
<script>
    function displayVals() {
    $("#multiple").val([1,3]);
      var singleValues = $("#single").val();
      var multipleValues = $("#multiple").val() || [];
      $("p").html("<b>Single:</b> " + 
                  singleValues +
                  " <b>Multiple:</b> " + 
                  multipleValues.join(", "));
    }

    $("select").change(displayVals);
    displayVals();

</script>

</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜