Javascript to output different messages depending on answer - javascript

I am trying to have a simple postcode search where the user enters their postcode to see if they qualify for support. I would like it to be that once they have pushed enter it shows the result, at the moment I have it as keyup.
Due to it being postcode, it needs to search both with and with the space and also upper and lower case. Im hoping someone can help.
You can view the code here:
https://jsfiddle.net/esdrxq0n/3/
HTML
<h1>Enter your postcode to see if you qualify</h1>
<input type="text" id="postcode" value="" />
<div id="container" style="display:none;">Our services support your postcode</div>
<div id="sorry" style="display:none;">Sorry we do not operate in your area. Signup to be notified when we do.</div>
JAVA
$("#postcode").bind('keyup', function (e) {
if (e.which >= 97 && e.which <= 122) {
var newKey = e.which - 32;
// I have tried setting those
e.keyCode = newKey;
e.charCode = newKey;
}
$("#postcode").val(($("#postcode").val()).toUpperCase());
});
var validcode = ('SS94QL','SS9 4QL','SS143JA','SS14 3JA');
$("#postcode").keyup(function () {
var code = $(this).val();
if (code === validcode) {
$("#container").show();
$("#sorry").hide();
} else {
$("#container").hide();
$("#sorry").show();
}
});

Try this,
Mainly you put the pre-defined codes inside an array, then you can transform the typed string to uppercase and see if it exists in the array
$("#postcode").bind('keyup', function (e) {
if (e.which >= 97 && e.which <= 122) {
var newKey = e.which - 32;
// I have tried setting those
e.keyCode = newKey;
e.charCode = newKey;
}
$("#postcode").val(($("#postcode").val()).toUpperCase());
});
var validcode = ['SS94QL','SS9 4QL','SS143JA','SS14 3JA'];
$("#postcode").keyup(function () {
var code = $(this).val().toUpperCase();
if (validcode.indexOf(code) > -1 ) {
$("#container").show();
$("#sorry").hide();
} else {
$("#container").hide();
$("#sorry").show();
}
});
#postcode {
width:50%;
height:40px;
background-color:#ffffff;
margin:0px auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Enter your postcode to see if you qualify</h1>
<input type="text" id="postcode" value="" />
<div id="container" style="display:none;">Our services support your postcode</div>
<div id="sorry" style="display:none;">Sorry we do not operate in your area. Signup to be notified when we do.</div>

Your validCode should be an array and then you can use the indexOf function to find if the entered code exists in the array or not
var validcode = ['SS94QL','SS9 4QL','SS143JA','SS14 3JA'];
$("#postcode").keyup(function () {
var code = $(this).val();
if (validcode.indexOf(code) > -1) {
$("#container").show();
$("#sorry").hide();
} else {
$("#container").hide();
$("#sorry").show();
}
});
JSFIDDLE

Related

Prevent more than one space between words

I have a function that prevents people putting numbers or any symbol but letters onkeypress into a text box due to ongoing problems with data entry.
<td><input type="text" name="name" onkeypress="return isAlfa(event)"></td>
Now some staff for reasons unknown put two spaces between words at random times. So I need to prevent them putting more than one space between words. I want to do this in the same function, but it keeps breaking.
function isAlfa(evt) {
evt = (evt || window.event);
var charCode = (evt.which || evt.keyCode);
if ((charCode > 32)
&& (charCode < 65 || charCode > 90)
&& (charCode < 97 || charCode > 122)
) {
return false;
}
return true;
}
How can I prevent them entering more than one space between words?
Neglecting all the other helpful suggestions and comments and strictly following the OP's requirements one has to ...
Adapt the return condition in a way that takes into account if, with the current keystroke, a whitespace sequence is going to be created.
Thus one has to implement a method that determines exactly that.
There might be some possible helper methods too.
code example ...
function isWhiteSpace(char) {
return (/\s/).test(char);
}
function willCreateWhitespaceSequence(evt) {
var willCreateWSS = false;
if (isWhiteSpace(evt.key)) {
var elmInput = evt.currentTarget;
var content = elmInput.value;
var posStart = elmInput.selectionStart;
var posEnd = elmInput.selectionEnd;
willCreateWSS = (
isWhiteSpace(content[posStart - 1] || '')
|| isWhiteSpace(content[posEnd] || '')
);
}
return willCreateWSS;
}
function isAlfa(evt) {
evt = (evt || window.event);
var charCode = (evt.which || evt.keyCode);
return ((
(charCode > 32)
&& (charCode < 65 || charCode > 90)
&& (charCode < 97 || charCode > 122)
) || willCreateWhitespaceSequence(evt)) ? false : true;
}
<input type="text" name="name" onkeypress="return isAlfa(event)"/>
This code will prevent multiple white spaces, that is, it will only allow 1 space and it will prevent two or more white spaces. You can configure the amount of white space you want to deny. I am not the author of the original code, but I made the modifications to make it work properly.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Your-title</title>
<meta charset="utf-8">
</head>
<body>
<form>
<label>Name</label>
<input type="text" name="YourInputName">
</form>
</body>
</html>
<label>Name</label>
<input type="text" name="YourInputName">
<script>
var field = document.querySelector('[name="YourInputName"]');
field.addEventListener('keyup', function (event) {
var userName = field.value;
userName = userName.replace(/\s{2,}/g, ' ');
field.value = userName;
});
</script>
may be try to use something like this. on your keypress event try to check the last value by using string substr method and if that gives you a space and current code is also a Space then prevent or do whatever you want to do with input.
function checkstuff(event){
if (event.target.value.substr(-1) === ' ' && event.code === 'Space') {
console.log('space pressed in sequence');
}
}
<input type='text' onkeypress="checkstuff(event)">
Rather than listening for and evaluating each key press it would be far simpler just to react to any and all input and then sanitise whatever was entered via a RegExp.
Example:
<input type=text id=myfield />
JS:
document.querySelector('#myfield').addEventListener('input', evt => {
evt.target.value = evt.target.value.replace(/[^a-z\s]/ig, '').replace(/\s{2,}/g, ' ');
});
That first replaces all non-letters and spaces with nothing, then replaces sequences of 2 or more spaces with a single space.

javascript input only numbers [duplicate]

Is there a quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes (plus '.')?
JavaScript
You can filter the input values of a text <input> with the following setInputFilter function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and all browsers since IE 9):
// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter, errMsg) {
[ "input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) {
textbox.addEventListener(event, function(e) {
if (inputFilter(this.value)) {
// Accepted value.
if ([ "keydown", "mousedown", "focusout" ].indexOf(e.type) >= 0){
this.classList.remove("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
}
else if (this.hasOwnProperty("oldValue")) {
// Rejected value: restore the previous one.
this.classList.add("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
else {
// Rejected value: nothing to restore.
this.value = "";
}
});
});
}
You can now use the setInputFilter function to install an input filter:
setInputFilter(document.getElementById("myTextBox"), function(value) {
return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp.
}, "Only digits and '.' are allowed");
Apply your preferred style to the input-error class. Here’s a suggestion:
.input-error{
outline: 1px solid red;
}
Note that you still must do server side validation!
Another caveat is that this will break the undo stack since it sets this.value directly.
This means that CtrlZ will not work to undo inputs after typing an invalid character.
Demo
See the JSFiddle demo for more input filter examples or run the Stack snippet below:
// Restricts input for the given textbox to the given inputFilter.
function setInputFilter(textbox, inputFilter, errMsg) {
[ "input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) {
textbox.addEventListener(event, function(e) {
if (inputFilter(this.value)) {
// Accepted value.
if ([ "keydown", "mousedown", "focusout" ].indexOf(e.type) >= 0) {
this.classList.remove("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
}
else if (this.hasOwnProperty("oldValue")) {
// Rejected value: restore the previous one.
this.classList.add("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
else {
// Rejected value: nothing to restore.
this.value = "";
}
});
});
}
// Install input filters.
setInputFilter(document.getElementById("intTextBox"), function(value) {
return /^-?\d*$/.test(value);
}, "Must be an integer");
setInputFilter(document.getElementById("uintTextBox"), function(value) {
return /^\d*$/.test(value);
}, "Must be an unsigned integer");
setInputFilter(document.getElementById("intLimitTextBox"), function(value) {
return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 500);
}, "Must be between 0 and 500");
setInputFilter(document.getElementById("floatTextBox"), function(value) {
return /^-?\d*[.,]?\d*$/.test(value);
}, "Must be a floating (real) number");
setInputFilter(document.getElementById("currencyTextBox"), function(value) {
return /^-?\d*[.,]?\d{0,2}$/.test(value);
}, "Must be a currency value");
setInputFilter(document.getElementById("latinTextBox"), function(value) {
return /^[a-z]*$/i.test(value);
}, "Must use alphabetic latin characters");
setInputFilter(document.getElementById("hexTextBox"), function(value) {
return /^[0-9a-f]*$/i.test(value);
}, "Must use hexadecimal characters");
.input-error {
outline: 1px solid red;
}
<h2>JavaScript input filter showcase</h2>
<p>Supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and all browsers since IE 9.</p>
<p>There is also a jQuery version of this.</p>
<table>
<tr>
<td>Integer</td>
<td><input id="intTextBox"></td>
</tr>
<tr>
<td>Integer >= 0</td>
<td><input id="uintTextBox"></td>
</tr>
<tr>
<td>Integer >= 0 and <= 500</td>
<td><input id="intLimitTextBox"></td>
</tr>
<tr>
<td>Float (use . or , as decimal separator)</td>
<td><input id="floatTextBox"></td>
</tr>
<tr>
<td>Currency (at most two decimal places)</td>
<td><input id="currencyTextBox"></td>
</tr>
<tr>
<td>A-Z only</td>
<td><input id="latinTextBox"></td>
</tr>
<tr>
<td>Hexadecimal</td>
<td><input id="hexTextBox"></td>
</tr>
</table>
TypeScript
Here is a TypeScript version of this.
function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean, errMsg: string): void {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) {
textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & { oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null }) {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
}
else if (Object.prototype.hasOwnProperty.call(this, "oldValue")) {
this.value = this.oldValue;
if (this.oldSelectionStart !== null &&
this.oldSelectionEnd !== null) {
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
}
else {
this.value = "";
}
});
});
}
jQuery
There is also a jQuery version of this. See this answer.
HTML5
HTML5 has a native solution with <input type="number"> (see the specification and documentation). The documentation has a working demo of this input type.
Instead of reading the value property, read the valueAsNumber property of the input to get the typed value as a number rather than a string.
Usage inside a <form> is recommended because validation is made easier this way; for example, pressing Enter will automatically show an error message if the value is invalid.
You can use the checkValidity method or the requestSubmit method on the entire form in order to explicitly check the validity.
Note that you might need to use the required attribute in order to disallow an empty input.
You can use the checkValidity method or the validity property on the input element itself in order to explicitly check the validity.
You can use reportValidity to show an error message and use setCustomValidity to set your own message.
This approach fundamentally has a different user experience: you are allowed to input invalid characters and the validation is performed separately.
This has the benefit that the undo stack (CtrlZ) won’t break.
Note that server-side validation must be performed, regardless, no matter which approach you choose.
But note that browser support varies:
Most browsers will only validate the input when submitting the form, and not when typing.
Most mobile browsers don’t support the step, min and max attributes.
Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see the Q&A Why does the HTML input with type="number" allow the letter e to be entered in the field?.
Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.
Demo
document.querySelector("form").addEventListener("submit", (event) => {
event.preventDefault();
console.log(`Submit!
Number is ${event.target.elements.number.valueAsNumber},
integer is ${event.target.elements.integer.valueAsNumber},
form data is ${JSON.stringify(Object.fromEntries(new FormData(event.target).entries()))}.`);
})
label {
display: block;
}
<form>
<fieldset>
<legend>Get a feel for the UX here:</legend>
<label>Enter any number: <input name="number" type="number" step="any" required></label>
<label>Enter any integer: <input name="integer" type="number" step="1" required></label>
<label>Submit: <input name="submitter" type="submit"></label>
</fieldset>
</form>
Use this DOM
<input type='text' onkeypress='validate(event)' />
And this script
function validate(evt) {
var theEvent = evt || window.event;
// Handle paste
if (theEvent.type === 'paste') {
key = event.clipboardData.getData('text/plain');
} else {
// Handle key press
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
}
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Here is a simple one which allows for exactly one decimal, but no more. The input event uses regex to replace text on the fly based on the two patterns:
Remove anything that's not a digit or a dot
Remove any second instance of a dot
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" />
As someone commented below, the solution above does not handle leading zeros. If your particular use case requires that these are not allowed you can add to the pattern above like so:
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />
That will allow 0.123 or .123 but not 0123 or 00.123.
I've searched long and hard for a good answer to this, and we desperately need <input type="number", but short of that, these 2 are the most concise ways I could come up with:
<input type="text"
onkeyup="this.value=this.value.replace(/[^\d]/,'')">
If you dislike the non-accepted character showing for a split-second before being erased, the method below is my solution. Note the numerous additional conditions, this is to avoid disabling all sorts of navigation and hotkeys. If anyone knows how to compactify this, let us know!
<input type="text"
onkeydown="return ( event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )">
Most answers here all have the weakness of using key- events.
Many of the answers would limit your ability to do text selection with keyboard macros, copy+paste and more unwanted behavior, others seem to depend on specific jQuery plugins, which is killing flies with machineguns.
This simple solution seems to work best for me cross platform, regardless of input mechanism (keystroke, copy+paste, rightclick copy+paste, speech-to-text etc.). All text selection keyboard macros would still work, and it would even limit ones ability to set a non-numeric value by script.
function forceNumeric(){
var $input = $(this);
$input.val($input.val().replace(/[^\d]+/g,''));
}
$('body').on('propertychange input', 'input[type="number"]', forceNumeric);
HTML5 has <input type=number>, which sounds right for you. Currently, only Opera supports it natively, but there is a project that has a JavaScript implementation.
And one more example, which works great for me:
function validateNumber(event) {
var key = window.event ? event.keyCode : event.which;
if (event.keyCode === 8 || event.keyCode === 46) {
return true;
} else if ( key < 48 || key > 57 ) {
return false;
} else {
return true;
}
};
Also attach to keypress event
$(document).ready(function(){
$('[id^=edit]').keypress(validateNumber);
});
And HTML:
<input type="input" id="edit1" value="0" size="5" maxlength="5" />
Here is a jsFiddle example
HTML5 supports regexes, so you could use this:
<input id="numbersOnly" pattern="[0-9.]+" type="text">
Warning: Some browsers don't support this yet.
I opted to use a combination of the two answers mentioned here i.e.
<input type="number" />
and
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
<input type="text" onkeypress="return isNumberKey(event);">
JavaScript
function validateNumber(evt) {
var e = evt || window.event;
var key = e.keyCode || e.which;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45) {
// input is VALID
}
else {
// input is INVALID
e.returnValue = false;
if (e.preventDefault) e.preventDefault();
}
}
additional you could add comma, period and minus (,.-)
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
HTML
<input type="text" onkeydown="validateNumber(event);"/ >
2 solutions:
Use a form validator (for example with jQuery validation plugin)
Do a check during the onblur (i.e. when the user leaves the field) event of the input field, with the regular expression:
<script type="text/javascript">
function testField(field) {
var regExpr = new RegExp("^\d*\.?\d*$");
if (!regExpr.test(field.value)) {
// Case of error
field.value = "";
}
}
</script>
<input type="text" ... onblur="testField(this);"/>
// In a JavaScript function (can use HTML or PHP).
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
In your form input:
<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>
With input max. (These above allows for a 12-digit number)
You can use pattern for this:
<input id="numbers" pattern="[0-9.]+" type="number">
Here you can see the complete mobile website interface tips.
A safer approach is checking the value of the input, instead of hijacking keypresses and trying to filter keyCodes.
This way the user is free to use keyboard arrows, modifier keys, backspace, delete, use non standard keyboars, use mouse to paste, use drag and drop text, even use accessibility inputs.
The below script allows positive and negative numbers
1
10
100.0
100.01
-1
-1.0
-10.00
1.0.0 //not allowed
var input = document.getElementById('number');
input.onkeyup = input.onchange = enforceFloat;
//enforce that only a float can be inputed
function enforceFloat() {
var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
if (!valid.test(this.value)) {
var n = this.value.match(number);
this.value = n ? n[0] : '';
}
}
<input id="number" value="-3.1415" placeholder="Type a number" autofocus>
EDIT: I removed my old answer because I think it is antiquated now.
One more example where you can add only numbers in the input field, can not letters
<input type="text" class="form-control" id="phone" name="phone" placeholder="PHONE" spellcheck="false" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
Please find below mentioned solution. In this user can be able to enter only numeric value, Also user can not be able to copy, paste, drag and drop in input.
Allowed Characters
0,1,2,3,4,5,6,7,8,9
Not allowed Characters and Characters through events
Alphabetic value
Special characters
Copy
Paste
Drag
Drop
$(document).ready(function() {
$('#number').bind("cut copy paste drag drop", function(e) {
e.preventDefault();
});
});
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="number" id="number" onkeypress="return isNumberKey(event)" placeholder="Enter Numeric value only">
Let me know if it not works.
If you want to suggest to the device (maybe a mobile phone) between alpha or numeric you can use <input type="number">.
A short and sweet implementation using jQuery and replace() instead of looking at event.keyCode or event.which:
$('input.numeric').live('keyup', function(e) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
Only small side effect that the typed letter appears momentarily and CTRL/CMD + A seems to behave a bit strange.
JavaScript code:
function validate(evt)
{
if(evt.keyCode!=8)
{
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key))
{
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
}
HTML code:
<input type='text' name='price' value='0' onkeypress='validate(event)'/>
works perfectly because the backspace keycode is 8 and a regex expression doesn't let it, so it's an easy way to bypass the bug :)
just use type="number" now this attribute supporting in most of the browsers
<input type="number" maxlength="3" ng-bind="first">
A easy way to resolve this problem is implementing a jQuery function to validate with regex the charaters typed in the textbox for example:
Your html code:
<input class="integerInput" type="text">
And the js function using jQuery
$(function() {
$('.integerInput').on('input', function() {
this.value = this.value
.replace(/[^\d]/g, '');// numbers and decimals only
});
});
$(function() {
$('.integerInput').on('input', function() {
this.value = this.value
.replace(/[^\d]/g, '');// numbers and decimals only
});
});
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous">
</script>
<input type="text" class="integerInput"/>
input type="number" is an HTML5 attribute.
In the other case this will help you:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="number" name="somecode" onkeypress="return isNumberKey(event)"/>
Just an other variant with jQuery using
$(".numeric").keypress(function() {
return (/\d/.test(String.fromCharCode(event.which) ))
});
I saw some great answers however I like them as small and as simple as possible, so maybe someone will benefit from it. I would use javascript Number() and isNaN functionality like this:
if(isNaN(Number(str))) {
// ... Exception it is NOT a number
} else {
// ... Do something you have a number
}
Hope this helps.
You can also compare input value (which is treated as string by default) to itself forced as numeric, like:
if(event.target.value == event.target.value * 1) {
// returns true if input value is numeric string
}
However, you need to bind that to event like keyup etc.
<input name="amount" type="text" value="Only number in here"/>
<script>
$('input[name=amount]').keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
</script>
My solution for a better user experience:
HTML
<input type="tel">
jQuery
$('[type=tel]').on('change', function(e) {
$(e.target).val($(e.target).val().replace(/[^\d\.]/g, ''))
})
$('[type=tel]').on('keypress', function(e) {
keys = ['0','1','2','3','4','5','6','7','8','9','.']
return keys.indexOf(event.key) > -1
})
Details:
First of all, input types:
number shows up/down arrows shrinking the actual input space, I find them ugly and are only useful if the number represents a quantity (things like phones, area codes, IDs... don't need them)
tel provides similar browser validations of number without arrows
Using [number / tel] also helps showing numeric keyboard on mobile devices.
For the JS validation I ended up needing 2 functions, one for the normal user input (keypress) and the other for a copy+paste fix (change), other combinations would give me a terrible user experience.
I use the more reliable KeyboardEvent.key instead of the now deprecated KeyboardEvent.charCode
And depending of your browser support you can consider using Array.prototype.includes() instead of the poorly named Array.prototype.indexOf() (for true / false results)
Use this DOM:
<input type = "text" onkeydown = "validate(event)"/>
And this script:
validate = function(evt)
{
if ([8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36].indexOf(evt.keyCode || evt.which) == -1)
{
evt.returnValue = false;
if(evt.preventDefault){evt.preventDefault();}
}
}
...OR this script, without indexOf, using two for's...
validate = function(evt)
{
var CharValidate = new Array("08", "046", "039", "948", "235");
var number_pressed = false;
for (i = 0; i < 5; i++)
{
for (Ncount = 0; Ncount < parseInt(CharValidate[i].substring(0, 1)) + 1; Ncount++)
{
if ((evt.keyCode || evt.which) == parseInt(CharValidate[i].substring(1, CharValidate[i].lenght)) + Ncount)
{
number_pressed = true;
}
}
}
if (number_pressed == false)
{
evt.returnValue = false;
if(evt.preventDefault){evt.preventDefault();}
}
}
I used the onkeydown attribute instead of onkeypress, because the onkeydown attribute is checked before onkeypress attribute. The problem would be in the Google Chrome browser.
With the attribute "onkeypress", TAB would be uncontrollable with "preventDefault" on google chrome, however, with the attribute "onkeydown", TAB becomes controllable!
ASCII Code for TAB => 9
The first script have less code than the second, however, the array of ASCII characters must have all the keys.
The second script is much bigger than the first, but the array does not need all keys. The first digit in each position of the array is the number of times each position will be read. For each reading, will be incremented 1 to the next one. For example:
NCount = 0
48 + NCount = 48
NCount + +
48 + NCount = 49
NCount + +
...
48 + NCount = 57
In the case of numerical keys are only 10 (0 - 9), but if they were 1 million it would not make sense to create an array with all these keys.
ASCII codes:
8 ==> (Backspace);
46 => (Delete);
37 => (left arrow);
39 => (right arrow);
48 - 57 => (numbers);
36 => (home);
35 => (end);
This is an improved function:
function validateNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
Here is my simple solution for React users only, I couldn't find a better solution and made my own. 3 steps.
First, create a state.
const [tagInputVal, setTagInputVal] = useState("");
Then, use the state as input value (value={tagInputVal}) and pass the event to the onChange handler.
<input id="tag-input" type="text" placeholder="Add a tag" value={tagInputVal} onChange={(e) => onChangeTagInput(e)}></input>
Then, set the value of the event inside onChange handler.
function onChangeTagInput(e) {
setTagInputVal(e.target.value.replace(/[^\d.]/ig, ""));
}

Backspace not working after using jquery class

For an input field I have used a class
Here code for input field:
<?php
echo $this->Form->input('duration', array('class'=>'input-large text-right number- field','value'=>'0'));
echo $this->Form->error('duration');
?>
Here the jquery class code:
$(".number-field").keypress(function(e) {
var code = e.which || e.keyCode;
if(code >= 48 && code <= 57) {
console.debug(code);
} else {
return false;
}
});
Main reason In input field use can't type character in digits field. This class working fine.But after type digits backspace not working. For example suppose I have typed 1956, now I want to edit it 1955. In here I am enable to cut 6 by backspace.
You can use following script -
$(".number-field").keypress(function(e) {
var code = e.which || e.keyCode;
//allow Backspace and Delete key.
if((code >= 48 && code <= 57) || code == 8 || code == 46) {
console.debug(code);
} else {
return false;
}
});
Similar to escaping the 'backspace' key you might want to escape the 'Delete' key(code == 46)
If you just want to allow the numbers in input type then you can use HTML5 input type number.
<input type="number" name="year">
You can use regex for this:
var reg = /^\d+$/; // only number
$(".number-field").keypress(function(e) {
var code = e.which || e.keyCode;
if(reg.test(String.fromCharCode(code))) {
console.debug(code);
} else {
return false;
}
});

adding text to a only numeric text field for usability?

OK so i have this task that im not sure how to achieve. I have a text field that is only allowing the users to enter numeric values....I am validating on keypress to make sure that only numeric numbers are allowed
That works well
My problem is that the client wants text after the numbers to say " Miles" so if the user enters 100 they see "100 Miles"
I guess for usability. Does anyone know a good technique or jquery plugin to do this
In addition to a javascript solution, you may also want to look into the HTML 5 pattern attribute for <input>. For example, in modern browsers you could do something like:
<input name="miles" pattern="^\d+\s?[Mm]iles$" required>
Which requires no javascript at all :) Here's the relevant spec.
How about this:
$('input').keypress(function(e) {
if (e.which < 48 || e.which > 57) {
// not a number
return false;
}
// gets current entered numer
var number = this.value.split(' ')[0];
// adds new number
number = '' + number + String.fromCharCode(e.which);
this.value = number + ' miles';
return false;
})
It would be easier and I think clearer to do this in some sort of tag just outside of the textbox. Have a span directly below or something then update it on your keypress.
$('#textBox').keydown(function(){
// Validation code
$('#someSpan').html($(this).val() + " Miles");
});
How about this http://jsfiddle.net/TmxSN/1/
$(function(){
var timerOutId;
$('#inp').keypress(function(e) {
var key = e.which;
clearTimeout(timerOutId);
try{
if(this.value){
this.value = $.trim(this.value.match(/\d+/g)[0]);
}
}catch(e){}
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
return false;
}
}).keyup(function(e) {
var textBox = this;
if(this.value){
timerOutId = setTimeout(function(){
textBox.value = $.trim(textBox.value.match(/\d+/g)[0]) + " Miles";
}, 2000);
}
})
});
My problem is that the client wants text after the numbers to say "
Miles" so if the user enters 100 they see "100 Miles"
Then you can handle it in the onfocus and onblur event of your input type="text" like this.
Try this
<input type="text" min="0" max="1000" step="1" id="distance" placeholder="Enter the value in miles"/>
And Script
$(document).ready(function() {
//$("#distance").keypress(PassNumbersOnly);
$("#distance").focus(OnFocus);
$("#distance").blur(OnBlur);
});
function OnFocus() {
var $this = $(this);
if ($this.val().indexOf("Miles") != -1) {
$this.val($this.val().split(" ")[0]);
}
}
function OnBlur() {
var $this = $(this);
if ($.trim($this.val()) != "") {
$this.val($this.val() + " Miles");
}
}
Demo here: http://jsfiddle.net/naveen/EQEMr/
Tell your client that anyone with enough intelligence to use the web can understand:
<label for="distance">Distance in miles:
<input type="text" name="distance" id="distance"></label>
and that doing anything else is:
confusing for users
problematic as javascript may or may not be enabled/available
of zero practical use for the business as the value must be validated on the server anyway
the value requires additional processing at the server to remove the appended characters

Jquery / window.onbeforeload in custom jquery function

I want to add to this code a "window.onbeforeload" event to show a message that prevent the user from quitting the current page without adding the products to cart.
I have to show only when the quantity in > than 0 and with respecting the code below.
How can I do that ?
<form> <p><input class="qty"
type="text" maxlength="1" value="0" /></p>
<p><input class="qty" name="text"
type="text" value="0" /></p> <p><input
class="qty" name="text2" type="text"
/></p> </form>
<script type="text/javascript">
$(".qty").change(function(e) {
if(this.value != '3' && this.value != '6' && this.value != '9') {
this.value = 0;
alert('You can buy only 3, 6, or 9 pieces fromn this product');
} }); </script>
Thanks for help :)
Not sure why everyone is suggesting globals. This method requires no globals and no change() listener (which you may still need if you want that alert there). Based on MDC, assuming support for [].indexOf:
window.onbeforeunload = function (e) {
var e = e || window.event;
if (['3','6','9'].indexOf($(".qty").val())>=0) {
return;
}
else {
var msg = 'You can buy only 3, 6, or 9 pieces from this product';
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = msg;
}
// For Safari
return msg;
}
};
With multiple inputs you will need to change the condition slightly:
var valid = true;
$('.qty').each(function(){ valid = valid && ['3','6','9'].indexOf($(this).val())>=0; });
if (valid) {
return;
}
else { ... }
You would need to set some "global" variable. GLobal does not necessarily mean global to the window, just enough it's global in your own namespace (which you hopefully got).
if(this.value != '3' && this.value != '6' && this.value != '9') {
NotifyTheUser = true;
}
else {
NotifyTheUser = false;
}
window.onbeforeunload = function() {
if( NotifyTheUser ) {
return 'Check your input.. foo bar yay!';
}
};
you can save the value in some global variable and then onbeforeunload look for that value, whether it's greater than 0 or not.
var valueContainer = 0;
$(".qty").change(function(e) {
valueContainer = this.value;
//rest of your code
});
window.onbeforeunload = function() {
if( valueContainer == 0) {
return 'Please Don't go away without selecting any product :(';
} };

Categories