using JQuery, I am trying to create a few textboxes that will only allow numeric values, no duplicate numbers, no empty spaces and allow only numbers in the range. I used the range from 1 to 999. This is my code so far. I have the numeric values and the duplication of numbers parts working but I am not sure how to prevent empty textboxes or maintain the range from 1 to 999 for each textbox. The range part does not seem to work and I haven't figured out how to prompt the user about empty textboxes yet. I think there is a way to use HTML5 to control the range but that method won't prompt the user if they are not within the range. Do you have any suggestions?
<html>
<head>
<script type='text/javascript' src='js/jquery.js'></script>
</head>
<form id="form1">
Enter some text: <input type="text" id="field1" />
<br /><br />
Enter some text: <input type="text" id="field2" />
<br /><br />
Enter some text: <input type="text" id="field3" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#field1').blur(function() {
if ($(this).val() == $('#field2').val() || $(this).val() == $('#field3').val()) {
$('#field1').stop(false,true).after(' <span style="color:red;" class="error">No duplicate values please!</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
});
$('#field2').blur(function() {
if ($(this).val() == $('#field1').val() || $(this).val() == $('#field3').val()) {
$('#field2').stop(false,true).after(' <span style="color:red;" class="error">No duplicate numbers please!</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
});
$('#field3').blur(function() {
if ($(this).val() == $('#field1').val() || $(this).val() == $('#field2').val()) {
$('#field3').stop(false,true).after(' <span style="color:red;" class="error">Duplicate values are not allowed!</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
});
});
function RangeTextBox(min, max) {
this.min = min;
this.max = max;
this.textboxbody = $("<input type='text'>");
// Check for a valid range
this.textboxbody.keyup(function(event) {
var textboxbody = event.target;
var value = parseInt(textboxbody.value);
var isNotNumeric = !/^[0-9]+$/.test(textboxbody.value);
var isOutsideRange = (value < min) || (value > max);
if (isNotNumeric || isOutsideRange) {
$(textboxbody).addClass('error');
}
else {
$(textboxbody).removeClass('error');
}
});
return this.textboxbody;
}
<!-- To use it in, simple create a new TextBox by calling new RangeTextBox(min, max). For example -->
$(document).ready(function() {
$("textboxbody").append(new RangeTextBox(1, 999));
});
</script>
</html>
$(document).ready(function() {
$("textboxbody").append(RangeTextBox(1, 999));
});
I would suggest you to use jquery validation plugin: http://docs.jquery.com/Plugins/Validation
Related
This is my form:
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
And this my jQuery that's not working:
$('.fms-quote-form').submit(function() {
if ( $('#fms-zip').val() >= 90000 AND <=96162 ) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
How do I (i) check that the value of #fms-zip is greater than 90000 and smaller than 96162 to submit the form, and (ii) redirect the user to another website if any other value is entered?
Look forward to your input :)
Always check the error console - you're assuming syntax that is faulty. AND will be throwing an error - you need &&.
What's more, you can't just specify your higher number and assume JavaScript will know to compare it against the same subject value you compared the lower value against - you have to repeat the subject.
let val = parseInt($('#fms-zip').val());
if (val >= 90000 && val <= 96162 ) { //<-- note 2 references to #val
As #Alessio Cantarella points out, you also need to cast the value to a number - reading the field's value returns a string.
To check if ZIP is greater than 90000 and smaller than 96162, you need to use:
parseInt function to convert #fms-zip's value to an integer
&& logic operator to check that both conditions are valid.
$(function() {
$('.fms-quote-form').submit(function() {
let zip = parseInt($('#fms-zip').val());
let isZipValid = zip >= 90000 && zip <= 96162;
if (isZipValid) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
You can try like this -
$(function() {
$('.fms-quote-form').submit(function() {
var valueZip= parseInt($('#fms-zip').val());
if (valueZip >= 90000 && valueZip <= 96162) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});
let's said i have a form for Quantity input with class txt-qty, and it will be loop based on data from database.
Than i want trying to check the value of quantity should not be 0, but if one of the quantity is bigger than 0 it will be true
this is my code that what i have tried :
<script type="text/javascript">
$(document).ready(function(){
var input_qty = false;
$('#checkout').submit(function(e){
e.preventDefault();
var qty = $('.txt-qty').each(function(){
$(this).val();
});
if(qty > 0){
input_qty = true;
}else{
input_qty = false;
}
if(input_qty == false){
alert('You must input one of quantity from the menu list');
}else{
this.submit();
}
});
});
</script>
in my script if i alert qty it would be return [object],[object].
guys can you help me how to check one of the value of quantity should not be 0?
If the goal is to check that at least one of the .txt-qty fields has a value > 0, then you can use get() to get a true array from your jQuery object and then Array#some to see if any field's value is > 0:
$(document).ready(function() {
$('#checkout').submit(function(e) {
e.preventDefault();
if (!$('.txt-qty').get().some(function(e) { return $(e).val() > 0; })) {
// Gets array ---^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// | Checks for at least one with a value > 0
alert('You must input one of quantity from the menu list');
} else {
this.submit();
}
});
});
That relies on implicit conversion of the string value to a number; you might consider using parseInt instead.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#checkout').click(function(e){
e.preventDefault();
var qty =[];
$('.txt-qty').each(function(){
if(parseInt($(this).val(),10) <= 0 )
{
qty.push($(this).val());
}
});
if(qty.length > 0){ // check this
input_qty = true;
}else{
input_qty = false;
}
if(input_qty == true){
alert('You must input one of quantity from the menu list');
}else{
this.submit();
}
});
});
</script>
</head>
<body>
<input type='text' class='txt-qty' />
<input type='text' class='txt-qty' />
<input type='text' class='txt-qty' />
<input type='text' class='txt-qty' />
<input type='text' class='txt-qty' />
<input type='text' class='txt-qty' />
<input type='submit' id='checkout'/>
</body>
</body>
</html>
What is the most efficient way to set the range for an input-field to -100.0 to 100.0? I would like to check every character. Other characters than -,0,1,2,3,4,5,6,7,8,9 and . are not allowed. Values without floating point, e.g. 78, are also possible.
UPDATE
I need a solution for IE, so html5 solution with type="range" or type="number" are useless for me.
The only code I have is the input field:
<input type="text" id="zahlenwert" value="" />
The question is: Do I have to check every character with onKeydown() or is there a smarter way?
Here is what you are looking for:
http://jeroenvanwarmerdam.nl/content/resources/javascript/jquery/spincontrol/jquery-spincontrol-1.0.zip
And here is example:
http://jeroenvanwarmerdam.nl/content/resources/javascript/jquery/spincontrol/jquery-spincontrol.html?x=31&y=10
Integration:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery-numeric.js"></script>
<script type="text/javascript" src="jquery-number-selector.js"></script>
<script type="text/javascript" src="jquery-spincontrol-support.js"></script>
<script type="text/javascript" src="jquery-spincontrol.js"></script>
<!-- SpinControl definition -->
<script type="text/javascript">
(function($) {
$(function() {
$(":number").addClass("number").spinControl({ folder: "images/" });
});
})(jQuery);
</script>
Here is your body html code:
<input type="number" max="10" min="-10" step="0.5" />
I'm partly guessing at your requirements but if you're just trying to restrict the input value to a number within a specific range you could use HTML5's range input type:
<input type="range" name="myrange" min="-100" max="100">
Or use JavaScript to validate the value like in this demo fiddle:
document.getElementById('test').onchange = isNumber;
function isNumber(){
var val = this.value;
var aNumber = !isNaN(val);
var aNumberNotOverOneHundred = (Math.abs(parseFloat(val, 10)) <= 100);
alert((aNumber && aNumberNotOverOneHundred)?"Yarp":"Narp");
}
Or use input pattern attribute to validate against a regex pattern.
This is the solution I wanted:
$(document).ready(function() {
$("input#zahlenwert").keyup(function(){
var zahlenwert= $("input#zahlenwert").val();
var status = 0;
for(i=zahlenwert.length;i>0;i--){
if(status==0){
if(zahlenwert.length == 0){
}
else if(zahlenwert.length == 1 && zahlenwert.match(/^(-|[0-9]) /)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 2 && zahlenwert.match(/^(-[0-9]|[0-9],|[1-9][0-9])/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 3 && zahlenwert.match(/^(-[1-9][0-9]|[0-9],[0-9]|100|[1-9][0-9],|-[0-9],)/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 4 && zahlenwert.match(/^(-100|100,|[1-9][0-9],[0-9]|-[0-9],[0-9]|-[1-9][0-9],)/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 5 && zahlenwert.match(/^(100,0|-100,|-[1-9][0-9],[0-9])/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 6 && zahlenwert.match(/^-100,0/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else{
zahlenwert = zahlenwert.substring(0,zahlenwert.length-1);
$("input#zahlenwert").val(zahlenwert);
console.log("Error!!!");
}
}
}
});
});
<script type='text/javascript'>
function required()
{
var empt = document.forms["form1"]["Name"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+ the function will return false.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
For flexibility and other places you might want to validated. You can use the following function.
`function validateOnlyTextField(element) {
var str = element.value;
if(!(/^[a-zA-Z, ]+$/.test(str))){
// console.log('String contain number characters');
str = str.substr(0, str.length -1);
element.value = str;
}
}`
Then on your html section use the following event.
<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />
You can always reuse the function.
I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?
Part of the Login
<form name="myForm">
<label for="firstname">Age: </label>
<input name="num" type="text" id="username" size="1">
<input type="submit" value="Login" onclick="return validateForm()">
function validateForm()
{
var z = document.forms["myForm"]["num"].value;
if(!z.match(/^\d+/))
{
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
Edit:
RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.
Simply omit the negating ! and use if(/\D/.test(z)).
here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers
This one worked for me :
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Late answer,but may be this will help someone
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
Validate numbers in JavaScript - IsNumeric()
function validateNumber(e) {
const pattern = /^[0-9]$/;
return pattern.test(e.key )
}
<input name="username" id="username" onkeypress="return validateNumber(event)">
This approach doesn't lock numlock numbers, arrows, home, end buttons and etc
The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
Javascript Approach
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
jQuery Approach
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
The above answers are for most common use case - validating input as a number.
But to allow few special cases like
negative numbers & showing the invalid keystrokes to user before
removing it, so below is the code snippet for such special use cases.
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
Regular expressions are great, but why not just make sure it's a number before trying to do something with it?
function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
if(Number(sum)) {
alert(sum);
} else {
alert("Numbers only, please!");
};
};
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.
I think we do not accept long structure programming we will add everytime shot code see below answer.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >
Using the form you already have:
var input = document.querySelector('form[name=myForm] #username');
input.onkeyup = function() {
var patterns = /[^0-9]/g;
var caretPos = this.selectionStart;
this.value = input.value.replace(patterns, '');
this.setSelectionRange(caretPos, caretPos);
}
This will delete all non-digits after the key is released.
var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
elem[i].addEventListener('keypress', function(event){
var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
var validIndex = keys.indexOf(event.charCode);
if(validIndex == -1){
event.preventDefault();
}
});
}
If you are using React, just do:
<input
value={this.state.input}
placeholder="Enter a number"
onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component {
state = {
input: '',
}
onChange = e => {
let input = e.target.value.replace(/[^0-9]/g, '');
this.setState({ input });
}
render() {
return (
<div>
<input
value={this.state.input}
placeholder="Enter a number"
onChange={this.onChange}
/>
<br />
<h1>{this.state.input}</h1>
</div>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
</script>
// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:
$(document).ready(function () {
$(".nosonly").keydown(function (event) {
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
alert("Only Numbers Allowed"),event.preventDefault();
}
}
});
});
Avoid symbols like "." "," "+" "-". I tried it and it works fine.
$('#example').keypress(function (evt) {
if (evt != null && evt.originalEvent != null && /\D/.test(evt.originalEvent.key)) {
evt.preventDefault();
evt.stopImmediatePropagation();
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="example" id="example">