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.
精彩评论