views:

496

answers:

2

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?

+3  A: 

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();
Bogdan Constantinescu
+9  A: 

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();
ybo
whoops...that's right. I should delete my answer,..
Clyde
They may not perform as well as $('#foo'), but unless it's a problem, don't worry about it. Premature optimization and all that.
Andrew Hedges
@Andrew, you're completely right, users wouldn't see the difference in most cases. It's more a best practice, especially considering that the name might not be unique.
ybo