user1328021
user1328021

Reputation: 9840

Javascript alert only initiating for top row in a table

I'm trying to make an alert set off every time a button is clicked on, which is a column in a table.

However, the alert is only working when the user clicks the button in the top row. All rows below it does not work. Why?!

<span class="inline" id="part-name" style="font-size:20px;font-weight:bold;"> {{unipart.part}}</span>



    <td id ="Buy">
                <a class="btn btn-warning" href="{{offer.buynow_url}}">BUY NOW </a>
            </td>


<script type="text/javascript">
$('#Buy').click(function() {
   var myPart = $('#part-name').text();
   alert (myPart);
});
</script>

Note I have tried with id="Buy" in both the td tag, and also the a tag.

Upvotes: 0

Views: 148

Answers (4)

David L
David L

Reputation: 33833

If you want to bind to multiple DOM elements, bind to a class that they share instead (make a new class and use that class on each element).

Your DOM structure seems somewhat confusing, but if I understand it correctly, this should work.

<span class="inline" id="part-name" class="part-name" style="font-size:20px;font-weight:bold;"> {{unipart.part}}</span>

<td class="buy" id ="Buy">
            <a class="btn btn-warning" href="{{offer.buynow_url}}">BUY NOW </a>
        </td>


<script type="text/javascript">
$('.buy').click(function() {
   var myPart = $(this).closest('tr').children('.part-name').text();
   alert (myPart);
});
</script>

Upvotes: 1

shaneburgess
shaneburgess

Reputation: 15882

Perhaps you might want to do something like this:

   <span class="inline" id="part-name-{{partID}}" style="font-size:20px;font-weight:bold;"> {{unipart.part}}</span>



    <td class ="Buy">
                <a class="btn btn-warning" href="{{offer.buynow_url}}" partId="{{partID}}">BUY NOW </a>
            </td>


<script type="text/javascript">
$('.Buy').click(function() {
   var myPart = $("#part-name-"+$(this).attr("partId")).text();
   alert (myPart);
});
</script>

This will break validation unless you are using HTML5.

Upvotes: 0

hoylemd
hoylemd

Reputation: 456

This is because you're selecting the s by their ids. Id's are supposed to be unique, so jQuery is grabbing the first one. If you use classes it will work better.

<span class="inline" id="part-name" style="font-size:20px;font-weight:bold;"> {{unipart.part}}</span>

<td class='Buy'>
  <a class="btn btn-warning" href="{{offer.buynow_url}}">BUY NOW </a>
</td>


<script type="text/javascript">
$('.Buy').click(function() {
  var myPart = $('#part-name').text();
  alert (myPart);
});
</script>

Upvotes: 0

Exception
Exception

Reputation: 8379

Instead of ID "Buy", give class name 'Buy' then use the below code

 $('.Buy').on('click',function(){
     alert($('#part-name').text());
 });

Upvotes: 0

Related Questions