psmyrdek
psmyrdek

Reputation: 119

Add or remove class in change event handler not working

I have a problem with addClass / removeClass methods in change method event handler.

I've registered my handler like this:

$('.someSelector').change(MyHandler);

and in MyHandler I have

function MyHandler(){
  var input = $(this);
  input.addClass('something'); //not working
}

after page loading I'm getting once again this input via console, I'm executing the same code and everything works correctly. So what's the problem with change method?

Upvotes: 2

Views: 924

Answers (2)

JGV
JGV

Reputation: 5187

You are very close. Try this:

$(document).ready(function () {      
  $('.someSelector').change(MyHandler);      
});

function MyHandler(){

  var input = $(this);
  input.addClass('something'); 
}
.something{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="someSelector">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

Upvotes: 1

dfsq
dfsq

Reputation: 193311

after page loading I'm getting once again this input via console, I'm executing the same code and everything works correctly

So it means that you didn't have DOM ready when you attempted to bind event for the first time. Try this:

$(function() {
    $('.someSelector').change(MyHandler);
});

Upvotes: 2

Related Questions