Any idea what is best practice for getting the value out of a form input field (that is second in the markup after it's label)?
I have been able to get the rest of the values fine (SKUs and price) but quantity is tricky.
JSFIDDLE to whole thing: /
Here is some jQuery that scopes the first tr of the table and then attempts to get into that row and pull out the quantity value:
var BSKfirstQTY = $(BSKfirstrow).find('td.quantity').text('input value');
But as you can see from the fiddle's result pane, it's spewing out [object Object]
.
NOTE: Leaving the .text() empty results in the it picking up the word Qty in the fiddle result pane (which is the label, not the number).
Any help would be hugely appreciated :)
Any idea what is best practice for getting the value out of a form input field (that is second in the markup after it's label)?
I have been able to get the rest of the values fine (SKUs and price) but quantity is tricky.
JSFIDDLE to whole thing: http://jsfiddle/hslincoln/7HXBQ/33/
Here is some jQuery that scopes the first tr of the table and then attempts to get into that row and pull out the quantity value:
var BSKfirstQTY = $(BSKfirstrow).find('td.quantity').text('input value');
But as you can see from the fiddle's result pane, it's spewing out [object Object]
.
NOTE: Leaving the .text() empty results in the it picking up the word Qty in the fiddle result pane (which is the label, not the number).
Any help would be hugely appreciated :)
Share Improve this question asked Mar 19, 2014 at 14:16 Harry LincolnHarry Lincoln 6562 gold badges10 silver badges30 bronze badges 2-
I sometimes prefer the jQuery/native hybrid:
$(BSKfirstrow).find('td.quantity')[0].value
– Martijn Commented Mar 19, 2014 at 14:21 - It's because you try to use .val() on your td instead of your input. instead of doing .find('quantity').val() just do .find('quantity input').val() – Robin Leboeuf Commented Mar 19, 2014 at 14:23
2 Answers
Reset to default 7If you pass an argument into text()
, you are setting the content of td.quantity
to that string, and JQuery will return the object for chaining. If you call text()
with no argument, you will get the text inside the element.
You should use .val()
to retrieve the values of input/textarea/selects elements, like so:
var BSKfirstQTY = $(BSKfirstrow).find('td.quantity input').val();
For more info on val vs. text, see this question.
Check out Difference between val() and text() He says that .text() won't work on input elements.
.val()
http://api.jquery./val/
.text()
http://api.jquery./text/
I think there's not really a "best practice" scenario, since they both do different things. It just seems like it's the same, but if you're working with a form you really want to use .val()
. Otherwise .text()
might suffice.