1

My requirement is to uncheck the checkbox if the textbox value is greater than 0. But it is unchecking after two key downs. I cant identify the error... Please someone help me.

     $('#'+QID+' TABLE TBODY TR').find("input[type='text']").live('keydown',function()
      {
       if($(this).val().length > 0)
       {
            $('#'+ExQID+' TABLE TBODY TR').siblings('TR').find(':checkbox').prop('checked',false)
       }
      });
Reddy
  • 1,327
  • 3
  • 23
  • 44
  • I think this is related to http://stackoverflow.com/questions/6581946/how-to-restore-textbox-data – andyb Jul 06 '11 at 11:04
  • 1
    @ApoY2k: 56% is perfectly acceptable. – Lightness Races in Orbit Jul 06 '11 at 11:05
  • possible duplicate of [Text box text capture using Jquery always 'one character behind'](http://stackoverflow.com/questions/1676435/text-box-text-capture-using-jquery-always-one-character-behind) – Lightness Races in Orbit Jul 06 '11 at 11:06
  • Have you thought about what will happen if the user enters a value into the textbox via some medium other than a key press? What if the user right clicks and pastes some text in? Or if the user clicks on an autocomplete suggestion? [This question](http://stackoverflow.com/questions/3314240/detecting-autocomplete-on-form-input-with-jquery/3314247#3314247) discusses these issues. – Spycho Jul 06 '11 at 11:10

2 Answers2

5

keydown fires before the value changes in the DOM.

So:

  • the first time the event fires, you're inserting the first character into the textbox but the DOM doesn't know this yet, so $(this).val().length is still 0;

  • the second time the event fires, you're inserting the second character into the textbox, and $(this).val().length is 1 from the last time.

Instead, use the keyup event, which fires after the textbox value is updated.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

use keyup insted of keydown

 $('#'+QID+' TABLE TBODY TR').find("input[type='text']").live('keyup',function()
      {
       if($(this).val().length > 0)
       {
            $('#'+ExQID+' TABLE TBODY TR').siblings('TR').find(':checkbox').prop('checked',false)
       }
      });
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193