0

Hi I want to restrict zero and dot for a field and it is working, But when the field is in pop up then the below code is not working.

<script>
  $('#name').keypress(function(e){ 
       if (this.selectionStart == 0 && e.which == 48 || this.selectionStart == 0 && e.which == 46 ){
          return false;
       }
    });
  </script>
logee
  • 5,017
  • 1
  • 26
  • 34
user9130953
  • 449
  • 2
  • 13

3 Answers3

2

Since your modal's DOM is generated dynamically on click event, $('.abc').keypress doesn't bind to it (because the modal's DOM doesn't exist yet).

You could make use of event bubbling in such cases. In your case, you could declare the event handler like:

$(document).on('keypress', '.abc', function(e){ 
   if (this.selectionStart == 0 && (e.which == 48 || e.which == 46) ){
      return false;
   }
});

This means all keypress events on an element with .abc will bubble up to the document, and the event handler will be triggered.

Here's the updated fiddle: http://jsfiddle.net/hcyj3q6q/398/

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
0

You are attaching click event on dynamically inserted element. For this

So instead of...

$(document).keypress('.abc', function(e){ 
   if (this.selectionStart == 0 && (e.which == 48 || e.which == 46) ){
      return false;
   }
});

You can write...

$(document).on('keypress', '.abc', function(e){ 
   if (this.selectionStart == 0 && (e.which == 48 || e.which == 46) ){
      return false;
   }
});

See this to know more How to add event on dynamically inserted HTML

cauchy
  • 1,123
  • 1
  • 9
  • 19
0

you can try like this(Javascript)

function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode == 48 || charCode == 46 
           )
             return false;

          return true;
       }

here I have created a fiddle https://jsfiddle.net/vinothsm92/8qde7gnk/2/

Vinoth
  • 972
  • 1
  • 16
  • 47