So I have this function:
function inputCheck()
{
var check = document.forms["drinkList"]["quant1"].value
if (isNaN(check))
{
window.alert("Input numbers only");
return false;
}
}
I am using this code to check if the user has entered a character into a textbox. If they did, then it will display an alert saying that it only accepts numbers.
Thing is, I have 11 more text boxes I have to run this function under.
Is there anyway I can get this to work, without recreating 11 more functions?
The other textbox names are:
quant2,
quant3,
quant4,
quant5,
whip,
cream,
sugar,
chocolate,
caramel2,
NOTE: I am also using onchange to make it a live check.
Sorry, didn't read clearly earlier. This should do, I guess.
<input onchange="inputCheck(this)">
function inputCheck(elem){
var check = elem.value;
if (isNaN(check))
{
window.alert("Input numbers only");
return false;
}
}
A more efficient way to hook an event to multiple inputs is to hook an event to a parent (like, say, <body>), and check the target of the events bubbling up:
var names = ['quant2', 'quant3', 'quant4', 'quant5', 'whip', 'cream', 'sugar', 'chocolate', 'caramel2'];
document.body.addEventListener('keyup', function (e) {
// skip event if it was NOT triggered on a matching element
if (names.indexOf(e.target.name) === -1) { return; }
// code to process event...
});
As asides:
Use <input type="number">. This is a facility provided by the browser, it will work immediately at input-time, among other niceties (like providing a number-only keypad on mobile devices instead of a full keyboard). Here's documentation and browser support for further reading.
I recommend checking the built-in feature input type=number
However, if you really want to check it for yourself you could do something like:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function numberOnly() {
var value = this.value;
if (!isNumber(value)) {
console.dir('not a number!'); // replace this with your ALERT
this.classList.add('error');
} else {
this.classList.remove('error');
}
}
var inputs = document.querySelectorAll('.number-only'); // selects all the inputs that have the class .number-only
[].forEach.call(inputs, function(input) {
input.addEventListener('keyup', numberOnly); // validate the input using the numberOnly onkeyup
});
input {
display: block;
margin: 5px;
border: 1px solid #aaa;
padding: 5px 10px;
}
input.error {
outline-color: #f00;
border: 1px solid #f00;
position: relative;
}
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
why don't use jquery,it can select all textbox if add same class, example:nonNumberTextbox.
$("#drinkList .nonNumberTextbox").each(function(index, node) {
if (isNaN(node.value)) {
window.alert("Input numbers only");
return false;
}
});
In your code isNaN(check) will always return false. This is because the .value property of an input element always returns a string and isNaN of a string is false.
You need to coerce check to a number before passing it to isNaN. I would suggest using the unary operator +. You also need to make sure that check is not empty or an all white-space string because the unary plus will those will coerced them to 0.
if (check.trim() === '' || isNaN(+check)) {
Alternatively depending on your needs you could use parseInt or parseFloat which will return NaN when parsing an empty or all white-space string.
if (isNaN(parseInt(check, 10))) { // if only integers are allowed
}
if (isNaN(parseFloat(check))) { // if integers and decimals are allowed
}
Yet another alternative would be to use a regular expression to validate the string without coercion.
if(!/^\d+$/.test(check)) { // if the number needs to be an integer
}
if(!/^\d+(?:\.\d*)?$/.test(check)) { // if the number can be an integer or a decimal
}
Try if this works
var textboxes = ['quant2', 'quant3', 'quant4', 'quant5', 'whip', 'cream', 'sugar', 'chocolate', 'caramel2'];
for (var i = 0; i < textboxes.length; i++ ){
var check = document.forms["drinkList"][textboxes[i]].value;
if (isNaN(check)){
window.alert("Input numbers only");
break;
}
}
Related
I have a form where a user enters a number, say an employee ID number or something like that. The field is set to reject anything that's not a number, so they can't just put in "bob" or faceroll the keyboard or whatever. Otherwise I'd convert this to a string.
I need to further validate and make this form reject anything that doesn't match the correct number of digits, lets say 5. It also needs to count leading zeros. For example - let's assume an Employee ID of 01234, which should match 5 digits. Currently, I'm losing that leading zero and it's rejecting values like the example above.
So, how can I:
count the number of digits in this number,
preserve leading zeros,
make sure they user is obligated to enter a number, with a JavaScript formula?
You should go with your original idea and use a string for such a field.
You can check whether the string is a number with a simple regex such as
let regex = /^[0-9]*$/;
regex.test(string);
It should return true if the string contains only digits.
If you get the input element's value with element.value it will return a string that preserves leading zeroes.
Limiting the input field's characters is covered in HTML text input allow only numeric input
I've copied and modified the example below to show an input field that only accepts up to 8 numbers and will log the ID on submit.
// Restricts input for the given textbox to the given inputFilter.
// Source: https://stackoverflow.com/a/469362
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
textbox.addEventListener(event, function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
});
});
}
const inputField = document.getElementById("employee-id");
const submitButton = document.getElementById("submit");
setInputFilter(inputField, function(value) {
return /^\d*$/.test(value) && (value.length <= 8);;
});
submitButton.addEventListener('click', event => {
console.log(inputField.value)
})
User ID: <input id="employee-id">
<button id="submit">submit</button>
Try this.
<input id="number" type="text" minlength="5" maxlength="5" value="42" pattern="\d{5}">
Check validity via JS
document.querySelector('#number').checkValidity()
check validity via CSS
input {
outline: none;
border: 1px solid green;
}
input:invalid {
border: 1px solid red;
}
if you need further validation just use javascript to validate it.
Javascript , how to return false when fill number till 10 decimal ?
This is my code for fill mobile number. I tried to set have to return false when user fill number into input == 10 decimal but not work , how can i do ?
<p style="margin-bottom: 20px;">
<input name="mobile_number" onKeyUp="check_mobile_number_length(this.value)" type="number" class="feedback-input" id="mobile_number" onchange="updateInput_mobile_number(this.value)">
<span id="mySpan_mobile_number" style=" float: left; margin-left: 12px; ^margin-left: 0px; font-size: 12px; color: red;"></span>
</p>
<script>
function check_mobile_number_length(mobile_number_value){
var mobile_number_value = mobile_number_value.replace(/[^0-9,.]+/g, "");
document.getElementById("mobile_number").value = mobile_number_value;
var mobile_number_value = document.getElementById("mobile_number").value;
if(mobile_number_value.length==10)
{
document.getElementById("mobile_number").style.border = "1px solid rgba(72,72,72,0.4)";
document.getElementById("mySpan_mobile_number").innerHTML = "";
return false;
}
else
{
document.getElementById("mobile_number").style.border = "1px solid red";
document.getElementById("mySpan_mobile_number").innerHTML = "please enter mobile number for 10 decimal";
}
}
</script>
By the time the user's key has been released, the character has already been typed. Hence, you can't use onkeyup for this. Here, I have used onkeypress, which fires when a key has been pressed.
Also, while return false works when directly inline, here it would be better to directly refuse the event, by passing the event to the function, and then calling .preventDefault() on it. This prevents the default action after the event (i.e. for onkeypress prevents the key being pressed, for onclick prevents the click, etc).
Here, I have created a basic example of how this can be done. Hopefully you can adapt it to meet your needs:
function check_mobile_value(ele, ev) {
if (ele.value.length>=10) {
ev.preventDefault();
}
}
<input type="number" onkeypress="check_mobile_value(this, event)">
Hello guys need some help here. i want to have limit the numbers inputted in my input field by putting max attribute to it. i have no problem with that until i use my keyboard to input data on it. seems like the max attribute is not filtering the input coming from the keyboard.
e.g
<input type="number" max="5" />
i can't go until 6 using the up and down arrow but when i manually put 6 using keyboard it's accepts it. how can i prevent? thank you
You would need to use JavaScript to do it. This will not let the user enter a number higher than 5:
<input type="number" max="5" onkeyup="if(this.value > 5) this.value = null;">
Another possible solution is to completely block the keyboard input by replacing onkeyup=".." event in the code above with onkeydown="return false".
have no problem with that until i use my keyboard to input data on it.
seems like the max attribute is not filtering the input coming from
the keyboard
This is how HTML5 validation/constraint work. However, it will invalidate when the form submits. Alternatively, you can validate it yourself. To validate yourself, you need to wire up Javascript and call the checkValidity() on the input element.
checkValidity() of the constraints API will check the validity state of the element and will return the state of whether the input element validate or not. This will also set the validity object on the input so that you can query more details.
Ref: https://html.spec.whatwg.org/multipage/forms.html#constraints and https://html.spec.whatwg.org/multipage/forms.html#form-submission-algorithm
You can also use the :invalid selector in CSS to highlight invalid inputs.
Example Snippet:
var input = document.getElementById('test'),
result = document.getElementById('result');
input.addEventListener('blur', validate);
function validate(e) {
var isValid = e.target.checkValidity();
result.textContent = 'isValid = ' + isValid;
if (! isValid) {
console.log(e.target.validity);
}
}
input[type=number]:invalid {
border: 2px solid red;
outline: none;
}
<label>Enter value and press tab: </label><br/>
<input id="test" type="number" min="1" max="10" />
<hr/>
<p id="result"></p>
You can use javascript to restrict the maximum input value to 5.
HTML
using oninput as a event handler
<input type="number" max="5" oninput="checkLength(this)" />
JS
function checkLength(elem) {
// checking if iput value is more than 5
if (elem.value > 5) {
alert('Max value is 5')
elem.value = ''; // emptying the input box
}
}
DEMO
An Utility Function to Solve Two Problem
Problem 1: Limit user input to maximum n digit
For this use n number of 9 as max parameter. As an example if you want to limit user input in 4 digit then max param value will be 9999.
Problem 2: Limit user input at a maximum value
This is intuitive. As an example If you want restrict the user input to maximum 100 then max param value will be 100.
function getMaxInteger(value, max) {
if(!value) return;
if( parseInt(value) <= max ) {
return value;
}
return getMaxInteger(value?.substr(0, value?.length-1), max);
}
function maxInt(value, max) {
return getMaxInteger(value?.replace(/\D/,''), max);
}
Use this maxInt method on input change handler
ngModelChange for Angular
onChange for React
v-on:change or watch for Vue
onkeyup="if(this.value > <?=$remaining?>) this.value = null; else if(this.value < 1) this.value = null;"
I'm not sure what I could be doing wrong, but why when I test the regular expression /^[\d{9}]*$/ on the website https://regex101.com/#javascript it match correctly if it's a number or not, but when I apply the RegEx on the JavaScript it doesn't work properly? I mean, its only showing red for numeric or characters. Instead green for numeric and red for characters.
HTML:
<input type="text" name="age" id="msisdn" onKeyUp="checkKey()">
JavaScript:
function checkKey() {
var msisdn = document.getElementById("msisdn");
if (msisdn.value == /^[\d{9}]*$/) {
msisdn.style.color = "#00b300";
} else {
msisdn.style.color = "#ff0000";
}
}
Code on fiddler
if(msisdn.value == /^\d{9}$/) { will compare the input value(string) against RegExp Object which will always return false.
Use RegExp#test
if(/^\d{9}$/.test(msisdn.value)) {
Updated Fiddle
And here's the shortest equivalent code
msisdn.style.color = /^\d{9}$/.test(document.getElementById("msisdn").value)
? "#00b300"
: "#f00";
Fiddle
JavaScript is not needed just to change the color of the text when it is not following the regex, HTML & CSS can be used. HTML5 pattern attribute can be used on the <input> and :valid and :invalid pseudo-selectors can be used in the CSS.
input:invalid {
color: #f00;
}
input:valid {
color: #00b300;
}
<input type="text" id="msisdn" name="plaintext" pattern="\d{9}">
Hello I have try a lot but can't solve . can any one explain me how I'll drive a JavaScript event after write" in " . I mean i wanted to make a div display:none to display:block after write " in ". that's a auto suggestion issue i've attaching a image the pattern is like that [word] [in] [word].
That's will do onkeyup event.
JS version...
var myInput = document.getElementById('myInput');
var messageBox = document.getElementById('messageBox')
myInput.addEventListener("keyup", checkString);
function checkString() {
var str = myInput.value;
// notice whitespace either side of "in" to prevent false positives
if (str.indexOf(' in ') > -1) {
messageBox.style.display = "block";
} else {
messageBox.style.display = "none";
}
}
#messageBox {
display: none;
padding: 15px;
background: #f2f2f2;
border: 1px solid #e6e6e6;
margin-top: 15px;
}
<input id="myInput" placeholder="Type here">
<div id="messageBox">In was typed</div>
Use input event in jQuery
$('#some_text_box').on('input', function() {
var value = $(this).val();
// do your stuff
// split the value by space and check if it contains 'in'
});
Using jQuery keyup event you can get value which user type in text box while user typing. Then with the use of indexOf javascript method you can compare string with in word. if match found you can display div otherwise hide that div.
Make sure to use toLowerCase() to convert string enter by user in lower case to get perfect match with in word. if user enter in in uppercase it function works fine.
DEMO
What is indexOf() method ?
The indexOf() method returns the position of the first occurrence of a
specified value in a string.
This method returns -1 if the value to search for never occurs.
Note: The indexOf() method is case sensitive.
$('#text').on('keyup', function() {
var value = $(this).val();
if(value.toLowerCase().indexOf(' in ') >= 0){
$('yourdiveselector').show()
}else{
$('yourdiveselector').hide()
}
});