javascript - number input numeric only -
this question has answer here:
- html text input allows numeric input 53 answers
i have project want numbers input i'm using input of type number allows decimal seperators etc. how prevent use of ,
.
, e
.
i have looked around , couldn't find 1 gave desired result, sinds either didn't block decimal inputs, or allow user still paste in field.
i have javascript , jquery can use, not want use external librairy.
if able me appriciated.
function limitkeys($id) { $field = document.getelementbyid($id); $value = $($field).val(); //if value contains multiple e , or . value no longer valid , gives me blank console.log($value); $regex = /[^\d]/; $val = $value.replace($regex, "");// cant replace in blank console.log($val); //$($field).val($val); } $('.number-only').keypress(function (event) { //sinds it's on keypress won't catch paste of data. console.log(this.value); var regex = new regexp("^[0-9]+$"); var key = string.fromcharcode(!event.charcode ? event.which : event.charcode); if (!regex.test(key)) { event.preventdefault(); return false; } });
try code
$(".number-only").on('input', function (e) { //if letter not digit display error , don't type if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { //display error message $(".error").html("only numbers allowed").show().fadeout("slow"); return false; } });
don't forget create error class.
Comments
Post a Comment