Sarvap Praharanayuthan
Sarvap Praharanayuthan

Reputation: 4360

removeClass() removes the class but jQuery remembering it

In HTML Page

<input type='text' name='quantity' id='quantity' />

<div class='submit'>Submit</div>`

In JS

$(document).ready(function(e)
{
   $('input#quantity').keyup(function()
   {            {
      if($.isNumeric($('input#quantity').val())==true)
      {
    $('.submit').addClass('submit_success');
      }
      else
      {
    $('.submit').removeClass('submit_success');
      }
   });


   $('.submit_success').click(function(e)
   {
      document.write("The DIV is clicked");
   });
});

So the idea is when anyone type a numerical value in the input box the the <div class='submit'> will be added a class 'submit_success' and will look like <div class='submit submit_success'>.

Observations:

  1. Add class 'submit_success' works properly on entering a numerical value.

  2. Remove class works properly when a user types alphabet or editing the numerical value with alphabet.

  3. Click function executes properly when a user enter numerical data and click on the <div>

The problem is occurs when,

STEP 1: User enter a number in the text box. So the add class part is executed.

STEP 2: Now the user delete the number he typed and write an alphabet in the textbox. Now the remove class part executed and the submit_success class is removed.

But still the click function active. When a user click on the <div> it writes in the screen "The DIV is clicked". But I guess it should not be executed.

How to solve this problem?

Upvotes: 0

Views: 340

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

Switching to on() instead of click() fixes the issue you describe. Also within the event handler for the keyup event $(this).val() can be used to retrieve the input's value instead of using the selector.

Javascript

   $('input#quantity').keyup(function()
   {            
      if($.isNumeric($(this).val())==true) //simplified
      {
        $('.submit').addClass('submit_success');
      }
      else
      {
        $('.submit').removeClass('submit_success');
      }
   });

   $(document).on('click', '.submit_success', function(e)
   {
      alert("The DIV is clicked");
   });

JS Fiddle: http://jsfiddle.net/snYrb/

Upvotes: 2

Related Questions