Numeric textbox by JQuery dynamically

84 Views Asked by At

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

There are 1 best solutions below

1
Bilal Siddiqui On BEST ANSWER

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>