I have a form that I'm trying to get data from a form using jquery and validate it. What is the best way to take data from a form to a variable using jquery?
-
use jquery selector to get value – Shih-En Chou Aug 08 '12 at 00:06
-
Another question similar to this: http://stackoverflow.com/questions/169506/obtain-form-input-fields-using-jquery – Marcelo Rodovalho Jun 12 '13 at 20:12
4 Answers
Here is the snippet that you can use -
$('#myForm').submit(function() {
// get all the inputs into an array.
var $inputs = $('#myForm :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
});
Got it from stackoverflow-link
Well here we go
This is the jQuery script:
function getData () {
$(document).ready(function() {
var myTextFieldValue = $('#myTextField').value;
alert('The value is: '+myTextFieldValue);
});
}
This is the HTML
<form action='#' method='whatever'>
<input type='text' id='myTextField' />
<input type='submit' onClick='getData()' />
</form>
NOTE: In order to make your script working you must import the jQuery Libraries
Like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
I Did not try the script so there could be some errors. Hope i was helpful to you Bye.
(For any help pm me)

- 4,212
- 5
- 22
- 36
there no way to get all the data from a form in one line of code. You have to retrieve it value by value.
if you have a <input id='some-id' >
just use var someId = $('#some-id').val();
. Now someId hold the value of the input
The val() function only return the value of the first matched element (if you don't know what i mean take a look at jquery selector (http://api.jquery.com/category/selectors/)
take a look at http://api.jquery.com/val/ to see the val function, it has some weird thing with the <textarea>
tag
And remember to always validate server side, even if you already did it client side, js securrity is very easy to bypass

- 802
- 1
- 5
- 18
-
1there is a way to get all the data from a form in one line of code using '$('#myform').serialize();' – Bishnu Paudel Aug 08 '12 at 00:24
-
-
@gilbertbw serializeArray() might be useful in your use case. http://api.jquery.com/serializeArray/ – Bishnu Paudel Aug 08 '12 at 01:01