0

I've the following code to make a textbox numeric only. It's working fine.

$( ".numeric" ).keypress(function( evt ) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      evt.preventDefault();
    }
});

<input id="RollNo" type="text" class="numeric">

But when I tried to make the textbox numeric dynamically on a combobox change event, it's not working.

The following is the combobox change event handler-

$("#ExamId").change(function(){
    var examName = $("#ExamId option:selected").text();
    if(examName == "O Level"){
        $("#RollNo").removeClass("numeric");            
    }
    else{
        $("#RollNo").addClass("numeric");
    }
});

Is there any way out to make it happen?

1
  • why not you use type="number"? Commented Oct 18, 2019 at 6:05

1 Answer 1

1

Jquery events are appended to DOM at time of load, so whether you add or remove class, the events are native to element.

You may use unbind to release a keypress event.

function handleKeyPress(evt) {
  evt = (evt) ? evt : window.event;
      var charCode = (evt.which) ? evt.which : evt.keyCode;
      if (charCode > 31 && (charCode < 48 || charCode > 57)){
        evt.preventDefault();
      }
}

$("#ExamId").change(function(){
    var examName = $("#ExamId option:selected").text();
    if (examName == "O Level"){
        $("#RollNo").unbind('keypress');
    }
    else {
        $('#RollNo').keypress(handleKeyPress);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="RollNo" type="text">

<select id="ExamId">
  <option value="">Select</option>
  <option value="O Level">O Level</option>
  <option value="1 Level">1 Level</option>
</select>

Sign up to request clarification or add additional context in comments.

1 Comment

Happy to help paul :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.