cute programmer
cute programmer

Reputation: 15

Jquery $(this) is not working inside on 'change' function

I would like to ask why $(this) is not working inside my on change function?

My goal is to hide the input if the checkbox is clicked.

$('#checkboxContactName').on('change', () => {
  if ($(this).prop('checked')) {
    console.log('is checked!');
    $(this).parent().next().css('display', 'none');
  } else {
    $(this).parent().next().css('display', 'block');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="form-group">
  <label class="control-label" for="#" title="Contact Name">Contact</label>
  <label class="checkbox-inline" style="float:right;"><input id="checkboxContactName" type="checkbox" /> Hide
  </label>
</div>

Upvotes: 0

Views: 58

Answers (3)

Sagar Jajoriya
Sagar Jajoriya

Reputation: 2375

When using the arrow function, you can access the element like this :

$('#checkboxContactName').on('change', (ev) => {
   if(ev.target.checked) {
        console.log('is checked!');
    } else {
        console.log("unchecked")
    }
});

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68665

Change the arrow function syntax to to function declaration or get the event parameter in the function and use event.currentTarget instead of this. You don't need to preserve outer context in the arrow function. The this must refer to that context which jQuery bound to it.

$('#checkboxContactName').on('change', function() {
     if($(this).prop('checked')) {
         console.log('is checked!');
         $(this).parent().next().css('display', 'none');
     } else {
         $(this).parent().next().css('display', 'inline-block');
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
    <label class="control-label" for="#" title="Contact Name">Contact</label>
    <label class="checkbox-inline" style="float:right;"  >
    <input id="checkboxContactName" type="checkbox"/> Hide
    </label>
    <input type="text">
</div>

Upvotes: 1

swaroop pallapothu
swaroop pallapothu

Reputation: 608

Try this. It will work. You need to change the arrow function to plain function

$('#checkboxContactName').on('change', function()  {
  if($(this).prop('checked')) {
    console.log('is checked!');
    $(this).parent().next().css('display', 'none');
  } else {
    $(this).parent().next().css('display', 'block');
  }
});

Upvotes: 1

Related Questions