Ken 99
Ken 99

Reputation: 35

When click a tag show alert - Jquery

My code in HTML :

<td id ="tdtest">
    <a id="atest" href="#">
         <span id="spantest">Show</span>
    </a>
</td>

and Jquery :

$(document).ready(function () {

    $("#tdtest #atest").on('click',function(){
        alert ("Success !!!");

    })
}

But when i click "Show" , it's not working.

Upvotes: 0

Views: 970

Answers (3)

Durgpal Singh
Durgpal Singh

Reputation: 11953

use div the place of td and your code is working.

<div id ="tdtest">
    <a id="atest" href="#">
         <span id="spantest">Show</span>
    </a>
</div>

JS

$(document).ready(function () {
   $("#tdtest #atest").on('click',function(){
      alert ("Success !!!");
   });
});

working fiddle here

Upvotes: 1

Sing
Sing

Reputation: 4052

  1. only use one id in selector
  2. put code after document ready, $(function(){ code here.. })

$(function(){
  $("#atest").on('click',function(){
    alert ("Success !!!");

  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<td id="tdtest">
    <a id="atest">
         <span id="spantest">Show</span>
    </a>
</td>

Upvotes: 0

Sarah Gro&#223;
Sarah Gro&#223;

Reputation: 10879

You can't have a standalone <td> without a table and table row surrounding it. As soon as you write valid markup, it works:

$("#tdtest #atest").on('click',function(){
    alert ("Success !!!");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
  <td id="tdtest">
    <a id="atest" href="#">
      <span id="spantest">Show</span>
    </a>
  </td>
</tr>
</table>

As suggested in other answers already, an ID is already a unique identifier for a DOM element, so there's actually no need to use two ids in a selector and it might even internally slow down finding the correct node.

Upvotes: 1

Related Questions