Reputation: 10758
I'm trying to update the contents of all elements with the id tag of "row_total" to "$0.00". I can't figure out how to use each() correctly. Whats written below only updates the first instance of #row_total.
$(document).ready(function() {
$("#reset_row_totals").live('click', function() {
$('#row_total').each(function() {
$(this).html("$0.00");
});
e.preventDefault();
});
});
heres a jsfiddle --> http://jsfiddle.net/uxLZm/3/
Upvotes: 1
Views: 84
Reputation: 36476
You have multiple <td>
s with the same id row_total
. This is invalid. IDs are meant to be unique so when you let multiple elements have the same ID, things may not work as expected.
Instead, use a class which can be applied to multiple elements. Apply the class to each <td>
which you want to reset and use the .class_name
CSS selector: jsFiddle
HTML:
<a href='#' id='reset_row_totals'>Reset Rows</a><br/><br/><br/>
<table>
<tr><td class='row_total'>$5.99</td></tr>
<tr><td class='row_total'>$3.50</td></tr>
<tr><td class='row_total'>$32.00</td></tr>
<tr><td class='row_total'>$9.99</td></tr>
</table>
JavaScript:
$(document).ready(function() {
$("#reset_row_totals").live('click', function(e) {
$('.row_total').each(function() {
$(this).html("$0.00");
});
e.preventDefault();
});
});
Upvotes: 4
Reputation: 6031
Your ID's are illegal html. try this change to your html:
<table>
<tr><td class='row_total'>$5.99</td></tr>
<tr><td class='row_total'>$3.50</td></tr>
<tr><td class='row_total'>$32.00</td></tr>
<tr><td class='row_total'>$9.99</td></tr>
</table>
$(document).ready(function() {
$("#reset_row_totals").live('click', function() {
$('.row_total').each(function() {
$(this).html("$0.00");
});
});
});
Upvotes: 2
Reputation: 53246
Of course it only updates the first element with the ID of row_total
. IDs are supposed to be just that, unique identifiers for elements.
Any selector for an ID will automatically return the first and only the first element with that ID. In this instance you need to use the class selector, and apply the class to the elements. I slightly edited your jsFiddle here > http://jsfiddle.net/uxLZm/5/
Just as a matter of interest, you are implementing $.each()
correctly.
Upvotes: 2
Reputation: 6825
The problem is you can only use one unique ID per page. JavaScript will only see the first one. Change it to a class and it should work.
Here's an updated jsfiddle with the change.
Upvotes: 2
Reputation: 78580
It's the fact that you are reusing id's. You can't have duplicate id's in HTML. Instead, use classes.
<td class='row_total'>$5.99</td>
$("#reset_row_totals").live('click', function() {
$('.row_total').each(function() {
$(this).html("$0.00");
});
e.preventDefault();
});
Upvotes: 4