jQuery text() and val() returning null
EDIT: Seems i didnt use an 'id' on my textarea, so that problem has cleared up but i'm still getting a few problems with text()
var e = $('textarea#cost-'+i).val(); // e = 1 (for first iteration)
alert($('p#subtotal-'+i).text()); // alert 'subtotal' which is the text in my p#subtotal-1
$('p#subtotal-'+i).text().replaceWith(e); // <- this is the problem, i think
alert($('p#subtotal-'+i).text()); // no alert box at all
and this time i made sure they all have ids.
The following code, generates an alert box with nothing in it. If i change it to val() it says 'undefined'
$('textarea.costbox').live('blur',function() {
for(var i in items) {
alert('iteration '+i);
alert('textarea#cost-'+i);
var e = $('textarea#cost-'+i).text();
alert('cost '+e);
}
});
<textarea name="cost-1" class="costbox"></textarea>
The idea for this code is to update a subtotal when the value has been changed. This is the last piece of the puzzle.
All the HTML looks normal when i inspect it in chrome. And all the rest of my code is working fine.
This sho开发者_如何学运维uld be running with modernizer1.7 and jQuery1.5.1, based off recent HTML5Boilerplate.
Here's another example of the same basic thing - http://jsbin.com/obeho5/3/edit
Its probably something simple but i've been stuck here for hours and can't see it.
[if its not something obvious and simple i can post more code]
#
is used to get by ID, your element has no ID just a name.
Either add an ID or use this:
'textarea[name="cost-'+i+'"]'
You did not include jQuery in your example. It works fine using .val()
: http://jsbin.com/obeho5/4/edit
Note: The others are right regarding the code you posted in the question, but the markup you have in the demo is different. In the demo the elements have IDs.
$('textarea#cost-'+i).text();
Is looking for a textarea with an ID
, you've given it a name, you need to do:
$('textarea[name="cost-' + i +'"]').text();
edit: for your updated issue:
$('p#subtotal-'+i).text().replaceWith(e);
should be
$('p#subtotal-'+i).text(e);
You don't need to worry about replaceWith, you can simply add the new text as a parameter of the method.
精彩评论