How to get value from <input> using jQuery?
I have hidden input fields such as:
<input name="foo" value="bar"> <input name="foo1" value="bar1"> I would like to get both of these values ββand send them to the server using jQuery. How to use jQuery selector mechanism to capture these values?
+6
Coocoo4cocoa
source share2 answers
Since "foo" and "foo1" are the name of the input fields, you cannot use the jQuery (#) id selector, but instead you must use the attribute selector:
var foo = $("[name='foo']").val(); var foo1 = $("[name='foo1']").val(); This is not the best option for performance. You'd better set the ID of the input fields and use the id selector (for example, $ ("# foo")) or at least provide an attribute selector context:
var form = $("#myForm"); // or $("form"), or any selector matching an element containing your input fields var foo = $("[name='foo']", form).val(); var foo1 = $("[name='foo1']", form).val(); +24
ybo
source shareYou should use id or classes to speed up the process of getting values.
ID version (provided that the input has id = 'foo')
var value1 = $('#foo').val(); Class version (assuming the input has class = 'foo')
var value1 = $('.foo').val(); +5
Bogdan constantinescu
source share