How do I take I / O from a form and store it in a JS variable?
I am creating a web application UI and have not done any internal operations yet.
For testing purposes, I want my forms to work, so I want to take the resulting data and store it in javascript variables so that I can access it using jQuery.
Everything I've looked at tells me how to pass js variables to a form and not vice versa.
Any ideas?
Thanks.
a source to share
var variable = $('#myInput').val()
... Or, if your form submits with GET
, you can look at the jQuery URL Parsing plugin to access the variables on the new page.
Edit:
Sample form (should be a simple text box):
<html>
<body>
<form action="#">
<input type="text" id="myInput" name="myInput"/>
</form>
</body>
</html>
With this form, you can use the above code example. By the way, you can use the method .val()
on any jQuery selector that returns form elements, eg. $('input:text').val()
will give you the value of all text input fields (as an array if there are multiple values).
a source to share
I came across this rather awesome question about how to serialize a JSON form with jQuery , which would be a good start.
You can also have a look at the jQuery Form plugin which provides a formSerialize method which
Serializes the form to a query string. This method will return a string in the format: name1 = value1 & name2 = value2
and also the fieldSerialize method which
Serializes the elements of the field into a query string. This is useful when you only need to serialize part of a form. This method will return a string in the format: name1 = value1 & name2 = value2
a source to share