How to prevent user from entering decimals? - javascript

I've got an order page on my site. Some order items can have decimal quantities, some can't.
What's the best way to prevent the user from entering decimal quantities? (Apart from an alert box and setting the field to zero)?

Intercept key events for the field, detect illegal characters upon input, keep them from getting entered in the field and add a temporary msg near the field (inserted into the page) that explains what characters or values are allowed. pop up alerts are a bad way to give feedback in the middle of typing.
Then, validate again before submission because there are other ways to get data into fields (drag/drop, copy/paste, etc...) that you might not have caught everything.
Here's a jQuery example of both an integer only and a decimal only field with temporary messages displayed when invalid keys are typed:
Working jsFiddle: http://jsfiddle.net/jfriend00/CkDTy/
$(".integer").keypress(function(e) {
if (e.which < 48 || e.which > 57) {
showAdvice(this, "Integer values only");
return(false);
}
});
$(".decimal").keypress(function(e) {
// 46 is a period
if (e.which != 46 && (e.which < 48 || e.which > 57)) {
showAdvice(this, "Decimal numbers only");
return(false);
}
if (e.which == 46 && this.value.indexOf(".") != -1) {
showAdvice(this, "Only one period allowed in decimal numbers");
return(false); // only one decimal allowed
}
});
function showAdvice(obj, msg) {
$("#singleAdvice").stop(true, false).remove();
$('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
$("#singleAdvice").delay(4000).fadeOut(1500);
}

Here's a little jQuery that prevents non-numerical inputs:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if(currValue.search(/[^0-9]/) != -1)
{
// Change this to something less obnoxious
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
});
});

You can add an event (on key press) and detect if a decimal point has been pressed by the user or not. Also on form submission, use regular expressions to check if the submitted data is correct (because the user can forge the data using live editor like firebug). Also make sure to double check that on your server side in case if user disabled javascript.
for example:
<input type="text" onkeypress="checkDecimal();" />
<input type="submit" onclick="checkBeforeSubmit();" />
function checkDecimal() {
// your code goes here
}
function checkBeforeSubmit() {
// your code goes here
}
You better to use the same function cause it's basically the same thing and invoke it from both events.
On server side, check the submitted data again

Related

How we can apply validations to any field of a WordPress plugin

This is my website URL http://saloon.ekvitech.com/schedule-appointment/ on this page I am using a 'easy-appointment-plugin' of WordPress to book an appointment. Here when you fill the appointment form step by step then you are towards to personal information form. When you fill this then the form is submitted for review by admin. But the problem is in that form there is a phone field and that field was accepting alphabet as well as digits. This should be not done with the phone as we know that phone number will accept only digits.
So I need to validate this field with digits only. If someone enters alphabets then error message arrises digits only.
I applying my code in the "header.php" file, I am stuck with my script code because the fields are autogenerated by WordPress plugin and all fields have same class how we can achieve this and validate should be done on single filed i.e. on phone field only.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
//called when key is pressed in textbox
jQuery(".custom-field").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
jQuery(".col-sm-8").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
</script>
Note: My script will hide all fields don't know why. Please help me out form this sticky situation.
Many Thanks!
try this code:
jQuery(document).ready(function () {
//called when key is pressed in textbox
jQuery(document).on("keypress","input[name='phone']",function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
alert('number only');
return false;
}
});
});

Input allow numbers and only one letter/symbol

I have an input which I want to put a bar code using an scanner (bar code contains only numbers) the problem is that maybe I want to scan a bar code more than once, in this case I want to be able to do something like this:
10*bar code number
Right now I'm able to allow only numbers in my input with this code:
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
But with this I'm only able to type numbers, what can I do to allow type a determinate letter/symbol in this case: *
In other words I want a Regex that allows numbers and only this symbol " * ". I tried doing something like this:
if (/\D/g.test(this.value)) this.value = this.value.replace(/^[0-9*]+$/,'')"
But this only allows letters and symbols.
In this cases you should work on char validation and on input value.
The regular expression help validating just the final input, but to do a better job you should avid all not valid input on keyDown event.
And validate the whole input on the keyUp value.
Consider this example:
function onKeyDown(event) {
if (event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 16 || event.keyCode == 8)
return true;
event.preventDefault();
return false;
}
function onKeyUp(event) {
var value = event.target.value
if (!value.match(/^[0-9]+\*?[0-9]*$/)) {
event.preventDefault();
event.target.value = value.substring(0, value.length-1);
return false;
}
return true;
}
document.getElementById('inputSource').addEventListener('keydown', onKeyDown);
document.getElementById('inputSource').addEventListener('keyup', onKeyUp);
My input sample: <input type="text" value="" id="inputSource"/>

Alert and not allow if same word written twice in an input jquery or js

This is my input:
<input type='text' class='myprofiletags' name='my_profile_tags' value='' />
I want to alert and forbid the user if he/she writes the same word twice. I am entering values with commma e.g
games, animes, movies
jQuery('.myprofiletags').keypress(function(e)
{
if (jQuery(this).val().match(/,/g).length >= 10)
{
if(e.keyCode == 8 || e.keyCode == 46 || e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40)
{
}
else
{
e.preventDefault(); // stops the keypress occuring
alert('No more profile tags are allowed');
}
}
});
Set an event handler (onkeyup) on input box so that whenever user hits a key the handler gets called
In event handler take the values of input box and split them on comma
Check if any value is duplicate
If no return true
If yes show an alert
Synopsis:
$(".myprofiletags").keydown (function (e) {
alert ($(this).val());
});
You can also use change
$('input[name^="text"]').change(function() {
Edit: You are going in right direction, just split the value on comma and use each splitted value as an item of array.
See how to do that:
Split comma-separated input box values into array in jquery, and loop through it
Convert comma separated string to array

javascript passing input without entering input fields/forms

Yesterday i wrote a question here but the way i did that request was kinda confusing.
Now I'll try it different.
I have a barcode handscanner which just scans the barcode and writes the input into an input field.
It's just the same as a guy who typs 10 digits and presses return in less then 5ms.
example : 2134463342 + return
Now i have a form which was set to autofocus on reload and i can get the input from the scanner.
I want to be able to do scans and passing them into a database without entering the input field.
example: User does something else like browsing the webpage than the user scans something without entering the input field.
I have copied some code from a site:
var chars = [];
$(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
console.log(e.which + ":" + chars.join("|"));
if (pressed == false) {
setTimeout(function(){
if (chars.length >= 10) {
var barcode = chars.join("");
console.log("Barcode Scanned: " + barcode);
// assign value to some input (or do whatever you want)
$("#barcode").val(barcode);
}
chars = [];
pressed = false;
},500);
}
pressed = true;
});
});
$("#barcode").keypress(function(e){
if ( e.which === 13 ) {
console.log("Prevent form submit.");
e.preventDefault();
}
});
The code works fine, my Question is:
Is it possible to do that operation without entering the input field/form?
thanks
#alexMmM
did you tried CSS to hide the inputbox??? style= display:none or style= visibility:hidden property ???
It hides your input box and gives a virtual feel that it has been done without entering into input fields...

How to ignore unwanted characters from textbox (JavaScript or jQuery)

There's a TextBox that I wanna allow users to just enter numbers & not any alphabetical characters.
So how could I ignore those chars entered by end user via JavaScript or jQuery?
Notice I don't wanna replace user's entered value by empty string; Instead wanna ignore case if there is any way for it.
Try that code:
$("#id").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
return false;
}
});
reference http://roshanbh.com.np/2008/04/textbox-accept-only-numbers-digits.html
You want to attach a handler to the textbox's keypress event. In here check the event.which property to find out what key is pressed, and if it's not a number (between keycodes 48 and 57) return false, which will cancel the default behaviour of typing in the textbox.
$("input").keypress(function (e) {
if (e.which < 48 || e.which > 57)
return false;
});
I would not recommend intercepting keystrokes, allow the user to type whatever he/she wants, and validate on user action (submit/select etc).
Look at this jQuery plugin for instance: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
you said you didn't want to include alphabetical then you said you just want to ignore case? what do you need to do?
You can ignore lower case in JS by using string.toLowerCase()
For numeric-only I use this jQuery extension/plug in
http://www.texotela.co.uk/code/jquery/numeric/
In above options we can prevent the user from keyboard, but what if the user paste something, it will not restrict user to not paste any special character.
For example we are restricting it from keyboard with proper error msg
<script type="text/javascript">
$(function () {
$("#package").keypress(function (e) {
var keyCode = e.keyCode || e.which;
$("#lblError").html("");
//Regex for Valid Characters i.e. Alphabets and Numbers.
var regex = /^[A-Za-z0-9]+$/;
//Validate TextBox value against the Regex.
var isValid = regex.test(String.fromCharCode(keyCode));
if (!isValid) {
$("#lblError").html("Only Alphabets and Numbers allowed.");
}
else
{
$("#lblError").html("");
}
return isValid;
});
});
</script>
Now let's prevent it from pasting special character.
$('#package').bind("paste",function(){
var data= $('#package').val() ;
var removedNotAllowed = data.replace(/[^ws]/gi, '');
$( '#package' ).val(removedNotAllowed);
$("#lblError").html("Only Alphabets and Numbers allowed.");
});

Categories

Resources