ShadowFlame
ShadowFlame

Reputation: 3278

jQuery onClick preventDefault

I have a table of which I want to suppress the link clicks, because I need the links for other functionality.

The structure of the table is something like this:

<table>
<tr><th>Day</th><th>Event</th>
<tr class="DAY" id="DAY_0"><td>1-8-2013</td><td><a href="?tab=tabCalendar&dayEvent=DAY_0">Add Event</a></td></tr>
<tr class="DAY" id="DAY_1"><td>2-8-2013</td><td><a href="?tab=tabCalendar&dayEvent=DAY_1">Add Event</a></td></tr>
</table

my jquery code to try and block the from refreshing the page, and showing the id is this

<script>
  $("a").click(
      function(event) {
        event.preventDefault();
        alert('Picked: '+ event.target.id.slice(4) );
      }
    );
  </script>

I have also tried the following

$(".DAY").click(function(){//to catch the class DAY.click()

and even

$("[id^=DAY]").click(function(){//to catch the id DAY*.click

however, none of these function did anything.

The versions I use are

jquery-1.9.1.js
jquery-ui-1.10.3.custom.js

Upvotes: 21

Views: 62742

Answers (5)

Rushil Sablania
Rushil Sablania

Reputation: 536

Simplest approach:

<script>
   $(".DAY").click(
      function(event) {
         event.preventDefault();
         alert('Picked: '+ $(this).attr('id').slice(4));
      }
   );
</script>

Upvotes: 22

akakarikos
akakarikos

Reputation: 450

Maybe you need to modify to the following:

$("a").click(
function (event) {
    event.preventDefault();
    alert('Picked: ' + $(this).closest('tr').attr('id').slice(4));
});

Upvotes: 2

ajtrichards
ajtrichards

Reputation: 30530

Try this:

$(document).ready(function(){

    $("a").click(
      function(event) {
        event.preventDefault();

          DATA = $(this).closest('tr').attr('id').slice(4);

        alert('Picked: ' + DATA);
      }
    );

});

This will get select the ID of the a you clicked. I've also created this as a jSFiddle: http://jsfiddle.net/pAZeb/

Upvotes: 5

Arun P Johny
Arun P Johny

Reputation: 388446

You need to find the id of the closest tr of the clicked a

Try

jQuery(function($){
    $("a").click(function(event) {
        event.preventDefault();
        alert('Picked: '+ $(this).closest('tr').attr('id').slice(4) );
    });
});

Upvotes: 3

GautamD31
GautamD31

Reputation: 28773

Try to put the script in DOM READY

<script type="text/javascript">
    $(document).ready(function(){
        $("a").on('click',function(event) {
            event.preventDefault();
            alert('Picked: '+ $(this).parent('td').parent('tr').id.slice(4) );
        });
     });
</script>

Upvotes: 11

Related Questions