I have to hidden input fields such as:
<input name="foo" value="bar">
<input name="foo1" value="bar1">
I'd like to retrieve both of those values and POST them to the server using jQuery. How does one use the jQuery selector engine to grab those values?
The . val() method is primarily used to get the values of form elements such as input , select and textarea .
Answer: Use the jQuery . attr() Method attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.
As "foo" and "foo1" are the name of you input fields, you will not be able to use the id selector of jQuery (#), but you'll have to use instead the attribute selector :
var foo = $("[name='foo']").val();
var foo1 = $("[name='foo1']").val();
That's not the best option, performance-wise. You'd better set the id of your input fields and use the id selector (e.g. $("#foo")) or at least provide a context to the attribute selector:
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();
You should use id's or classes to speed up getting the value process.
ID version (assuming the input has id='foo')
var value1 = $('#foo').val();
Classes version (assuming the input has class='foo')
var value1 = $('.foo').val();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With