Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
Coocoo4Cocoa Avatar asked Mar 24 '09 17:03

Coocoo4Cocoa


People also ask

How can I get input value in jQuery?

The . val() method is primarily used to get the values of form elements such as input , select and textarea .

How do I find the value of an anchor tag?

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.


2 Answers

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();
like image 102
ybo Avatar answered Sep 20 '22 13:09

ybo


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();
like image 25
Bogdan Constantinescu Avatar answered Sep 21 '22 13:09

Bogdan Constantinescu