The HTML looks like this:
<div>
<label class="sr-only" for="product">Product</label>
<input id="product" type="text" placeholder="Product" maxlength="7" autofocus>
<label class="sr-only" for="batch">Batch</label>
<input id="batch" type="text" placeholder="Batch" maxlength="5">
</div>
The jQuery looks like this:
$('#product').on('keyup', function() {
let product = $(this).val().slice(0, 7);
let batch = $(this).val().slice(9, 14);
if ($(this).val() && $(this).val().length === 7) {
$(this).val(product);
$(this).next().focus().val(batch);
}
});
When I'm scanning the barcode, it reads this string WXYZ519 -8012456789.
I need to slice this string so that the input with id="product" and id="batch" gets the values as WXYZ519 and 80124 respectively without the hyphen and space in between.
The first input does receive the right value but I just couldn't get the second input to slice the right value into it.
Can anyone tell me why and what's wrong with my code?
Your range appears to be wrong if you wanted to get the entire 2nd half of the string.
If you change
$(this).val().slice(9, 14);
to
$(this).val().slice(9, $(this).val().length);
it will contain a string that starts at 9 and ends at the end of the string.
Another alternative which I believe is much cleaner and less error prone would be this:
let split = $(this).val().split(" -");
let product = split[0];
let batch = split[1];
Related
Here's a script, that will add all the Float values entered in input fields. But I am getting a problem at ROUNDING THE VALUE. With my script, Value before decimal point is rounding off after 0.99(like Price of an item). but I want to round off the value after 0.59(like minutes).
When the Calculate button is clicked, the value will be displayed in another input field.
function add_number() {
var first = parseFloat(document.getElementById("sunday").value);
var second = parseFloat(document.getElementById("monday").value);
var third = parseFloat(document.getElementById("tuesday").value);
var forth = parseFloat(document.getElementById("wednesday").value);
var fifth = parseFloat(document.getElementById("thursday").value);
var sixth = parseFloat(document.getElementById("friday").value);
var seventh = parseFloat(document.getElementById("saturday").value);
var rsl = first + second + third + forth + fifth + sixth + seventh;
document.getElementById("txtresult").value = rsl.toFixed(2);
}
<input type="number" name="sunhrs" id="sunday" />
<input type="number" name="monhrs" id="monday" />
<input type="number" name="tuesday" id="tuesday" />
<input type="number" name="wedhrs" id="wednesday" />
<input type="number" name="thurshrs" id="thursday" />
<input type="number" name="frihrs" id="friday" />
<input type="number" name="sathrs" id="saturday" />
<button onclick="add_number()">Calculate</button>
<br>
<br>
<input type="number" name="txtresult" id="txtresult" />
Example: If I entered 1.50,1.50 in input fields and click on calculate button the output will be 3.00 as the value is rounded off after 0.99. but i want the value rounded after 0.59 So, that the output will be 3.40.
Thanks in advance.
EDITED: The first problem in the post (it was befaore I change); the word "result" is special for JavaScript and I have not use it for a variable name.
Secondly, forgot to add element which has an id is txtresult
;) thx your attention.
In order to add these values together the way you want, you'll need to convert your inputs to fractional hours, and then convert back from fractional hours to the desired representation. JavaScript does not have an "hours" data structure built in. The JavaScript Number type has a decimal base, so it can only work like regular decimal numbers.
e.g.
var first = hoursFromString(document.getElementById("sunday").value);
//etc.
then
document.getElementById("txtresult").value = stringFromHours(result);
If you need help writing hoursFromString or stringFromHours, please update your question with more information on the part you're having trouble with.
I have an input box here
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" >
And I want to disallow users to enter the same numbers in the box? How can I do this ? Thanks in advance
I don't want them to be able to enter numbers like this
111111111
or
55555555
You can use a regular expression to find strings that only consist of one consecutive digit:
var validator = /\b(\d)\1+\b/
console.log(validator.test('111')) // true
console.log(validator.test('123')) // false
console.log(validator.test('121')) // false
console.log(validator.test('112')) // false
#edit If you don't want to let user enter these values as he types you may want to verify only when value equals to 2.
You can listen on keydown event of input element and verify it's actual content and pressed number like this:
var inputNode = document.getElementById('my_account');
inputNode.addEventListener('keydown', (event) => {
var inputValue = event.key;
var inputNodeValue = inputNode.value;
var length = inputNodeValue.length;
if (length === 1 && inputNodeValue[0] === inputValue) {
event.preventDefault();
}
});
If you want to verify on submit, just get value of first character and check if every other is equal to it.
Try this pattern:
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!(\d)\1{8}).*">
Notes:
you did not say you wanted to disallow letters, if you do, just replace .* with \d*
I interpreted it as "nine times the same number". If you want to e.g. not allow "3 times same number anywhere", you need to change it to ^(?!\d*(\d)\1{2,}).*
If you want to only disallow multiples of a digit without any other extra, add the line termination regex: ^(?!(\d)\1*$).*
Example for "not 3 times same number anywhere but must be numbers":
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!\d*(\d)\1{2,})\d*">
Example for "not only the same number multiple times but still numbers":
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!(\d)\1*$)\d*">
I have a normal input as follows:
<input type="number" name="quantity" id="myInput">
If I type "1." (without the quotes of course) when I try to get the value of the input with
document.getElementById("myInput").value
Only an empty string is obtained.
Is there any other way to get the "1." input with javascript?
Edit
I am working using Polymer 1.0 and databinding, so in my example I showed using normal JavaScript syntax with the intention of finding a solution to my problem using only javascript.
I just want to know how to access a property that returns the value of the input, and which I believe should be stored in some property of the object.
If you use <input type="number"> the element is enriched with an extra attribute, valueAsNumber. So instead of
document.getElementById("myInput").value
use
document.getElementById("myInput").valueAsNumber
valueAsNumber will return NaN instead of blank if the value entered in the input not is convertable to a number. There is also a validity attribute holding information of the status of the current value, both according to the value as supposed number but also according to the number input's settings, i.e "why is the number invalid".
Fun with number inputs, try this out in various browsers :
<input type="number" name="quantity" id="myInput" ><br>
<input type="text" id="value" ><br>
<input type="text" id="valueAsNumber" ><br>
<input type="text" id="validity" ><br>
document.getElementById("myInput").onkeyup = function() {
document.getElementById("value").value = this.value;
document.getElementById("valueAsNumber").value = this.valueAsNumber;
document.getElementById("validity").value = '';
for (validity in this.validity) {
if (this.validity[validity]) {
document.getElementById("validity").value+=validity+' ';
}
}
}
actually quite informative, if you want to investigate exactly why you get an empty value back from the input -> http://jsfiddle.net/oaewv2Lr/ Have tried with Chrome, Opera and FF - Chrome seems to be the most "forgiving" browser of those three.
I found a way to get invalid values:
Focus the input.
Select its contents using execCommand().
Grab the selection using window.getSelection().
Example:
document.querySelector('input[type="submit"]').addEventListener('click', function() {
var inp= document.getElementById('myInput');
inp.focus();
document.execCommand('SelectAll');
var value = window.getSelection().toString();
document.getElementById('output').textContent = value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="quantity" id="myInput">
<input type="submit">
<div id="output"></div>
It won't work if you will enter 1., as 1. is not a valid number.
Update: It seems that your use of type="number" means that certain values won't come back. You can switch it to a type="text" and do the checking yourself:
document.getElementById('mySubmit').addEventListener('click', function() {
var value = document.getElementById('myInput').value;
if ( value != parseFloat(value) )
alert('Invalid Number');
document.getElementById('myOutput').innerHTML = value;
});
<input type="text" name="quantity" id="myInput">
<input type="submit" id="mySubmit">
<div id="myOutput"></div>
I essentially have some weird voodoo stuff I have to fix.
This old classic asp code for generating textboxes looks like this
<%i3_addPhoneFields "requestorPhone1","Phone <font class =txtMedium>:<font color = red>*</font></font>",i3_EmpPhoneNumber%>
I see that the OUTPUT view source is
<input class="txtSmall" type="text" name="requestorPhone1" value="" size="3" maxlength="3">
<input class="txtSmall" type="text" name="requestorPhone1" value="" size="3" maxlength="3">
<input class="txtSmall" type="text" name="requestorPhone1" value="" size="4" maxlength="4">
I didn't know the name repeated 3 times is valid html
I cannot just add in ID's for each one
I cannot just go changing all this code for several reasons.
I have javascript variables for phone number like this:
(888) 433-3017
What I have is essentially added in Jquery
If I do this then ALL 3 text boxes will essentially get the same value (222 - obviously)
$('input[name="requestorPhone1"]').val('222');
GOAL
To use javascript / jquery with regex and to take
(888) 433-3017
For 1st textbox to put in 888 , 2nd textbox 433 , 3rd textbox 3017
Here's one approach for splitting the number and then populating it into textboxes:
function doIt() {
var myString = "(123) 456-7890"; //hard-coded number for demo
myString = myString.replace(/\D/g,''); //remove all non-numerics
console.log(myString);
//extract component parts from the full number string
var first = myString.substr(0,3); //extract the first part of number
var second = myString.substr(3,3); //second part
var third = myString.substr(6,4); //third part
console.log(first, second, third);
//use jQuery's eq() to select specific elements in order
$('input[name="requestorPhone1"]:eq(0)').val(first);
$('input[name="requestorPhone1"]:eq(1)').val(second);
$('input[name="requestorPhone1"]:eq(2)').val(third);
}
There's JSFiddle demo here: http://jsfiddle.net/hh2o1bek/
Obviously I've hard-coded the number, but this should be enough to point you in the right direction.
You could something like this:
var els = document.getElementsByClassName("txtSmall");
if (els[0])
els[0].value = "888";
if (els[1])
els[1].value = "433";
if (els[2])
els[2].value = "3017";
JS + Jquery :
str = '(888) 433-3017';
a = str.split(' ');
a[0] = a[0].replace(/[^0-9]/g, '');
b = a[1].split('-');
$('input[name="requestorPhone1"]').eq(0).val(a[0]);
$('input[name="requestorPhone1"]').eq(1).val(b[0]);
$('input[name="requestorPhone1"]').eq(2).val(b[1]);
https://jsfiddle.net/y9w8nwop/2/
When working with a JavaScript function I want to prevent characters from being entered into a form if they do not meet certain parameters. The original JavaScript code I used was:
function validateLetter() {
var textInput = document.getElementById("letter").value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
document.getElementById("letter").value = replacedInput;
}
That function worked while I was using only 1 input point in my form, however when I tried to use that function over multiple inputs it would only affect the first one in the form.
When creating a function that could be reused by multiple input boxes I got the following code:
function validateLetter(dataEntry){
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
}
catch(InputError) {
window.alert(InputError)
return false;
}
return true;
}
The form I am using to input information is:
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded">
<p>Enter your mother's maiden name:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the city you were born in:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter" name="letter" onkeypress="validateLetter()">
</p>
</form>
Does anyone know a way to translate the last line of the first function: document.getElementById("letter").value = replacedInput;
To something that can be re-used with the current code.
I tried:
dataEntry.value = replacedInput
But that did not seem to run/change the function at all
The problem is in textInput.replace() - you forgot the second parameter. So instead of textInput.replace(/[^A-Za-z]/g);, you need textInput.replace(/[^A-Za-z]/g, "");.
As noted in the MDN website:
The ID must be unique in a document, and is often used to retrieve the element using getElementById.
In your example above, you are using the same value for the ID attribute on all of the input fields. Also, the name attribute should be unique within forms. The answer provided here explains in greater depth. With that said, in the examples below I have modified your input fields in respect to the above.
First off, the initial function you provided was pretty close. One issue with it is that the replace() method would need a second parameter. This parameter can be a string or a function to be called for each match. In your case I believe you just want an empty string:
function validateLetter() {
var textInput = document.getElementById("letter").value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
document.getElementById("letter").value = replacedInput;
}
Secondly, you can reference the current input field that is invoking validateLetter() by passing it along to the function as a parameter using the keyword this.
onkeypress="validateLetter(this);"
On a sidenote: You might achieve a better user experience using onkeyup instead of onkeypress. The example below utilizes this event instead so you can compare and judge for yourself.
Here is everything put together in a working example:
function validateLetter(target) {
var textInput = target.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
target.value = replacedInput;
}
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded">
<p>Enter your mother's maiden name:
<input type="text" id="maiden" name="maiden" onkeyup="validateLetter(this);" />
</p>
<p>Enter the city you were born in:
<input type="text" id="city" name="city" onkeyup="validateLetter(this);" />
</p>
<p>Enter the street you grew up on:
<input type="text" id="street" name="street" onkeyup="validateLetter(this)">
</p>
</form>