1 year ago
#315332

Pankaj Sajekar
Jquery to allow negative and positive numbers on text field and negative sign should have 0 indexes
I need to validate a text field to accept only negative or positive numbers and indexing also matters. this is what I have tried so far.
this is HTML code
<input type="text" class="negativeaccept" >
here is Jquery
$(document).on('keypress','.negativeaccept', function(event) {
if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
$(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
this code only accepts a positive number with a decimal. I want a negative sign (-) of The 0 indexes.
i try this code and its working (event.which != 45 || $(this).val().indexOf('-') != -1) &&
but negative (-)sign enter any index. can you try this better than this a solution.
$(document).on('keypress','.negativeaccept', function(event) {
if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
$(this).val().indexOf('.') != -1) && (event.which != 45 || $(this).val().indexOf('-') != -1) &&
(event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="negativeaccept">
javascript
html
jquery
jquery-events
0 Answers
Your Answer