Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing values of inputs to variable array to create a URL string

The problem i’m trying to solve is I am wanting to have a simple stepped form on one page that gathers some basic data to create a URL string that then populates a calculator on another page.

I have the following code:

`var params = {
users: 500,
length: 24,
router: "Pay Monthly",
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var queryString = $.param(params);
var myurl = "/calculator/?" + queryString ;

$( ".results" ).click(function() {  
    window.history.pushState('', "", myurl);
});`

In the above example, the number of users (500), length (24) and router (Pay Monthly) are the variables I would like to pass into the code above in order to create a string which is appended onto the URL.

In principle the above works with the static values i’ve given it, but i’m just stuck on how to get the values from HTML inputs.

Can anyone help?

Thanks

I have tried passing the above into an array to be parsed but it doesn’t give the expected results.

>Solution :

You can use $.serialize with a <form> element containing all the inputs.

let queryString = $('form').serialize();
let myurl = "/calculator/?" + queryString;
console.log(myurl);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input name="users" value="500"/>
  <input name="length" value="24"/>
  <input name="router" value="Pay Monthly"/>
</form>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading