Reputation: 127
I have a table like so:
<table>
<tr id="green-row" class="green"><td></td></tr>
<tr id="red-row" class="red"><td></td></tr>
<tr id="blue-row" class="blue"><td></td></tr>
</table>
And then I have buttons on the same page (but separate from the table) like so:
<button id="add-green" class="green">Add Green Product</button>
<button id="add-red" class="red">Add Red Product</button>
<button id="add-blue" class="blue">Add Blue Product</button>
Is there a way to have the actions on each button correspond to its associated table row, without have to use the specific ID each time?
For example, I know I can do something like this:
$('#add-green').click(function() {
$('#green-row td').append('<p>Added Green Product</p>')
});
But rather than have to write that three times for each product, is there a simpler way to just "link" the table row and the button together with the same class or a rel or something? (I'm new to jquery as you can see.)
Fiddle: http://jsfiddle.net/mqp5ev2p/3/
Upvotes: 0
Views: 1650
Reputation: 535
This my help you
<table id="mytable">
<tr data-relation="green"><td></td></tr>
<tr data-relation="red"><td></td></tr>
<tr data-relation="blue"><td></td></tr>
</table>
<button class="mybtn" data-relation="green">Add Green Product</button>
<button class="mybtn" data-relation="red">Add Red Product</button>
<button class="mybtn" data-relation="blue">Add Blue Product</button>
<script type="text/javascript">
$(document).ready(function(){
$(".mybtn").click(function(){
var selected = $(this).attr("data-relation");
var valuetoappend = $(this).html();
$("#mytable tr").each(function(){
var relation = $(this).attr("data-relation");
if(selected===relation)
$(this).next().append(valuetoappend);
});
});
});
</script>
Upvotes: 1
Reputation: 11416
Just updated your Fiddle Fiddle:
$('button').click(function() {
var col = $(this).attr("class");
var colcopy = $(this).text();
$("td." + col).append(colcopy);
});
And added classes red, blue and green for the buttons and the td. Think you can adjust it further.
Upvotes: 1
Reputation: 25892
This will work in your specific case
$('button[id^="add"]').click(function(){
var idPart = $(this).attr('id').split('-')[1];
$('tr[id^="'+idPart+'"] td').append('<p>Added '+ idPart+' Product</p>');
})
It will add as Added red Product
If you want to get color name starts with capital letter. Use this line
$('tr[id^="'+idPart+'"] td').append('<p>Added '+ idPart.charAt(0).toUpperCase() + idPart.slice(1) +' Product</p>');
Upvotes: 0