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 valueShih-En Chou– Shih-En Chou2012-08-08 00:06:53 +00:00Commented Aug 8, 2012 at 0:06
-
Another question similar to this: stackoverflow.com/questions/169506/…Marcelo Rodovalho– Marcelo Rodovalho2013-06-12 20:12:12 +00:00Commented Jun 12, 2013 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
Comments
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)
1 Comment
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