6 に答える
$(document).ready(function() {
$('#contactNumber').keyup(function() {
var numbers = $(this).val();
$(this).val(numbers.replace(/\D/, ''));
});
});
This should replace any non-digit with an empty character *as they are put in, negating the need to search for more than one non-digit at a time.
None of the above worked for me but I found a solution that works perfectly for what I needed (to disallow special characters in an input field). Prevents and alerts user.
<script>
$("#userlogin").keypress(function(e) {
if (String.fromCharCode(e.which).match(/[^A-Za-z0-9_ ]/)) {
e.preventDefault();
alert("Special characters are not allowed. Use 'A-Z', 'a-z' and '0-9'.");
}
});
</script>
Seen this answered before. Check out http://www.texotela.co.uk/code/jquery/numeric/
And you can simply change your class id and have this code on your page:
$(document).ready(function(){
$(".numeric").numeric();
});
If you don't want to use jQuery, you could write your own function and call it onkeyup event
See: http://www.htmlcodetutorial.com/forms/index_famsupp_158.html
Another option is using step attribute:
http://www.w3.org/TR/html-markup/input.number.html#input.number.attrs.step.float
<input type="number" step="0.01" min="0" >
type="tel" is HTML 5, and not jqueryMobile. the later devices whose browsers support HTML 5 input types render these boxes fine. But for older versions, the additional scripts need to be there. The scrips are already posted in above answers.
$('#contactNumber').bind('keypress', function (event) {
event = event || window.event; canAdd = new Boolean(false);
canAdd = ((event.charCode > 47) && (event.charCode < 58) || (event.charCode == 32) || (event.charCode == 40) || (event.charCode == 41) || (event.charCode == 43) || (event.charCode == 45) || (event.charCode == 124));
if (!canAdd && event.charCode)
return false;
});
But better to use HTML5 tel attrubute
HTML :
input type="tel" (keypress)="isNumberKey($event)"
Script :
isNumberKey(evt: any) { < br >
// to accept only numbers in contact field<br>
if ( < br >
(evt.key >= '0' && evt.key <= '9') || < br >
evt.key == "Backspace" || < br >
evt.key == "Delete" || < br >
evt.key == "ArrowLeft" || < br >
evt.key == "ArrowRight" < br >
) { < br > //"Backspace" etc for 'firefox' browser<br>
return true; < br >
} < br >
return false; < br >
}