Reputation: 519
I need a function to loop all URL parameters and to auto select options based on id and value, plus auto check checkboxes based on name and value. I'm already using getUrlParameter
function found here: https://stackoverflow.com/a/21903119, so what I need is kind of a loop all parameters found in URL on document.ready and set select options and input checkboxes accordingly.
url: htt....// domain.com/ site / page?param1=val1¶m2=val2
and if match param1, param2 with any select option id or checkbox name: 1) if is select option check the corresponding value ... or 2) if is checkbox and if has the same value shown in url param check it
Edit: since someone edited my title I have to mention: it should be javascript, jQuery not an option for this situation.
Upvotes: 0
Views: 1404
Reputation: 18619
I tried to reach what you want, I hope this will help.
You can do it with this code:
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (i in sURLVariables) {
let sParameter =sURLVariables[i].split('=');
let name=sParameter[0]
let value=decodeURIComponent(sParameter[1])
//Here is a loop
//Do something for each name-value pair
let collection = document.getElementsByName(name)
for(j in collection){
//searching for matching names (for checkboxes)
if(collection[j].value=value)collection[j].checked=true
}
let node = document.getElementById(name)
//checking element by ID (for select lists)
if(node){
node.value=value
}
}
Example:
Query string:
?a=b&c=d&e=f
HTML:
<select id="a"><!-- Will be set to b-->
<option>a</option>
<option>b</option>
<option>c</option>
</select>
<input type="checkbox" name="c" value="d"/><!--Will be checked-->
<input type="checkbox" name="c" value="f"/><!--Will NOT be checked-->
<input type="checkbox" name="e" value="d"/><!--Will NOT be checked-->
Upvotes: 1
Reputation: 663
You can do something like this:
jQuery.each(parameters, function (index, item){
var element = elt.find("[name=" + item.name + "]");
if (element.is("select")) {
element.find("option[value=" + item.value + "]").prop("selected", true);
} else {
element.val(item.value);
}
});
Upvotes: 0