Arens Myzyri Arens Myzyri - 1 month ago 11
HTML Question

Select URL parameters with jquery and add them to script



I have a url link:

http://mywebsite.org/product/page?var_one=result1&var_two=result2&var_three=result3&var_four=result4


The parameters are dynamic so it will not be static numbers.
In my example are 4, but maybe less or more.

I have a jquery code that pre selects a dropdown:

jQuery(document).ready(function( $ ) {
$("#var_one").val("result1");
});


Now I want to, depending on the url parameters above to populate jquery code like:

jQuery(document).ready(function( $ ) {
$("#var_one").val("result1");
$("#var_two").val("result2");
$("#var_three").val("result3");
.
.
.
});

Answer

Use regex to form a array of key value pair based on the url and use forEach to loop through the array and add the value to the id using .text()

Hope this helps!

var a = "http://mywebsite.org/product/page?var_one=result1&var_two=result2&var_three=result3&var_four=result4"

var query = a.split('?')[1] //extract query param
var queries = query.split(/&/g) //extract key value pairs from query param
queries.forEach(function(el){ //loop through the key value pair
  var newElm = '<div id="' + el.split('=')[0] + '">'+el.split('=')[1]+'</div>' //create new elm
  $('body').append(newElm) //append into DOM Body
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>