Coocoo4Cocoa
Coocoo4Cocoa

Reputation: 50916

How to retrieve a value from <input> using jQuery?

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?

Upvotes: 8

Views: 21933

Answers (2)

ybo
ybo

Reputation: 17162

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();

Upvotes: 28

Bogdan Constantinescu
Bogdan Constantinescu

Reputation: 5356

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();

Upvotes: 5

Related Questions