开发者

JQuery Select Multiselect Options Based on Text Field

开发者 https://www.devze.com 2023-04-01 07:59 出处:网络
I have a form with a multiselect field with several options, which looks like this: <select id=\"testselect\">

I have a form with a multiselect field with several options, which looks like this:

<select id="testselect">
    <option value="Value A">Value A</option>
    <option value="Value B">Value B</option>
    <option value="Value C">Value C</option>
    ...
</select>

There's a related input field that, upon loading the form, receives comma-delimited text values from a query string (i.e. Value A, Value E). What I have been trying to do is have JQuery separate that text string by looking in between the commas and then matching the input va开发者_StackOverflowlues with the option values. If there is a value in the input field, then select the corresponding option by adding the attribute selected="selected".

Does anyone have any ideas? I didn't get very far into this before realizing that it's over my head. Many thanks in advance.


Try this

var values = "Value A, Value E";
var $options = $("#testselect option");
$.each(values.split(","), function(){
    $options.filter("[value='"+this+"']").attr("selected", true);
});


There are many ways to do this, but here is one such. http://jsfiddle.net/cBBkG/

Ive assumed that the "input" variable will contain whatever you get from the query string.

0

精彩评论

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

关注公众号