jingo_man
jingo_man

Reputation: 529

Jquery Focus Repeatedly Called

I have a form to collect data entry from the user with button clicks that inserts a value into a <table><td> cell. A global counter variable is used on the page. As the button's are pressed, it finds the relevant <td id="holeScore1" tabindex="1">-</td> (there are 9 of these) and matches to the current global counter value. When updated, the global counter is incremented.

I would like to add in the ability to tap / click a <td> cell to reset the global counter back to this tabindex number, to allow data entry corrections.

Currently, I have this code which is picking up the first click on the <td> cell. However, it just endlessly re-runs the alert() call... The only thing I can do is reload the page, then click the final alert() away.

<script>
   $( "td" ).focus(function() {
      alert($(this).attr('tabindex'));
   });
</script>

Note, I put in the tabindex value through researching & testing how to implement my desired behaviour, with a description on jquery.com's documentation for the .focus() function that modern browsers can accept this. I reverted to the <td> element and have progressed this far in getting it to detect a click.

Upvotes: 0

Views: 47

Answers (1)

Wesley Smith
Wesley Smith

Reputation: 19571

This is probably happening because when you click the td it gets "focus" and triggers your code and the focus goes to the alert box, then when you close the alert, the focus goes back to the last element which was the td which again triggers your code.

It sounds like you could use the "click" event for you needs instead, something like:

<script>
   $("#someTableId").on('click', 'td', function() {
      alert($(this).attr('tabindex'));
   });
</script>

Note the use of $("#someTableId").on('click', 'td' instead of simply $("td").click( Either would work but using .on like I did would ensure that:

a) any dynamically added td elements still work with the code

b) we only attach the listener to td elements in the target table, and not ALL td elements on the page

Upvotes: 1

Related Questions