8

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?

2 Answers 2

28

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();
Sign up to request clarification or add additional context in comments.

3 Comments

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, 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.
Alternatively you may access directly the field's value like in var v = $("#form [name='foo']").val ()
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.