Reputation: 372
I am using the following code to grab information from the URL to pre-fill forms, however, I am trying to get this to work with a multiple select if multiple options are provided.
$(function() {
//grab the entire query string
var query = document.location.search.replace('?', '');
//extract each field/value pair
query = query.split('&');
//run through each pair
for (var i = 0; i < query.length; i++) {
//split up the field/value pair into an array
var field = query[i].split("=");
//target the field and assign its value
$("input[name='" + field[0] + "'], select[name='" + field[0] + "']").val(field[1]));
}
});
Multiple Select Example
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
I would like to be able to do http://www.example.com?strings=Test,Prof or something similar. I am new to JQuery and not sure of this.
Upvotes: 0
Views: 2578
Reputation: 8670
you can use javascript as in this fiddle: http://jsfiddle.net/yqh5u762/
document.getElementById("strings")[2].selected = true;
document.getElementById("strings")[1].selected = true;
You can't tell the box to change it's value because only one is allowed, but you can tell the individual options to show selected. This does require you to use the index number involved with the array of options.
Upvotes: 0
Reputation: 36448
You can pass an array as the value to set multiple
select values.
A simple approach, looking for the presence of ,
to indicate multiple values (so do something smarter if ,
is a valid character in other fields' values):
var query = 'strings=Test,Prof';
//extract each field/value pair
query = query.split('&');
//run through each pair
for (var i = 0; i < query.length; i++) {
//split up the field/value pair into an array
var field = query[i].split("=");
//target the field and assign its value
var parts = field[1].split(',');
if (parts.length > 1)
$("select[name='" + field[0] + "']").val(parts);
else
$("input[name='" + field[0] + "'], select[name='" + field[0] + "']").val(field[1]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name='strings' id="strings" multiple style="width: 100px">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
Upvotes: 1