Detect as soon as the input field is populated through barcode scanner - javascript

I have two input fields productName and quantity, productName field is getting populated using a barcode scanner(don't have access to code), my requirement is to detect as soon as the value gets populated in productName fields so that I can parse the value and populate the second field quantity.
<input type="text" id="productName" name="productName">
<input type="text" id="quantity" name="quantity">
Since I don't have access to code that scans the barcode and populate the productName field, there is one possibility which I think of is repeatedly checking if the field has value or not like below
myVar = setInterval(checkValue, 1000);
function checkValue(){
var productName= document.getElementById("productName");
console.log("running");
if (productName && productName.value) {
document.getElementById("quantity").value=productName.value;
clearInterval(myVar);
}
}
But I am looking for a better approach in vanilla Javascript, is there an alternate solution?

You can use onchange.
Example:
const productNameField = document.querySelector('#productName');
const quantityField = document.querySelector('#quantity');
const populateQuantityField = () => {
quantityField.value = productNameField.value;
}
productNameField.addEventListener('change', populateQuantityField);
Further Reading:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onchange

Related

detect as soon as there is value populated using javascript or entered using keyboard in input field

I have written this code which detects if there is a value populated in productName field using javascript and then it parses and auto-populate the input field quantity. My code only works if productName field is populated through javascript code and fails to register keyboard inputs if I use onChange
I want to detect in both scenarios i.e javascript and keyboard, how do I detect using the keyboard in this code?
const input = document.getElementById('productName');
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value');
Object.defineProperty(input, 'value', {
set: function(t) {
console.log('Input value was changed programmatically');
descriptor.set.apply(this, arguments);
document.getElementById("quantity").value=t
},
get: function() {
return descriptor.get.apply(this);
}
});
var i=0;
function changeInput(){
/* console.log(document.getElementById('productName').value) */
document.getElementById("productName").value=i++;
}
<input type="text" id="productName" name="productName" placeholder="product name">
<input type="text" id="quantity" name="quantity" placeholder="quantity">
<button onclick="changeInput()">Change</button>
Since I am a beginner in Javascript, a comment by #epascarello helped me, and this was quite easy with binding the input element:
document.getElementById("productName").addEventListener("input",(event)=>{
document.getElementById("quantity").value= document.getElementById("productName").value;
})

Set HTML Form Input To JS Variable

I want to read user input into a form back to them, sort of a confirmation before they send it in. I have some text elements on the page with their corresponding IDs. I would think that I just need to set the variables equal to the values of the input field, but when the function runs it just returns blank.
I have a function that sets the variables to the .value of that form input, but where I might be getting hung up is that there is no default value on the input field, I would think that the value is set after the user inputs something.
Example user inputs "John Doe" into field shouldn't that change the value of that field to "John Doe"?
var Phone;
document.getElementById('confirm-details').onclick = ConfirmDetails()
function ConfirmDetails() {
// Set variable to form input
Phone = document.getElementById("InputPhone").value;
// Change text element to variable
document.getElementById("BookingPhone").innerHTML = Phone;
};
Maybe I'm just confused about the .value attribute but I thought that the value on an input field should be what the user inputted.
This row
document.getElementById('confirm-details').onclick = ConfirmDetails()
should be
document.getElementById('confirm-details').onclick = ConfirmDetails
You don't want that document.getElementById('confirm-details').onclick references the result of the function ConfirmDetails (here void) but the function itself.
Instead of using .value, you need to be using .innerText
Phone = document.getElementById("InputPhone").innerText;
object.oninput = function(){
ConfirmDetails();
};
or, shorthand:
object.oninput = function(){ConfirmDetails()};
You should also use document.getElementById().innerHTML() to get the text
This worked just fine for me. I appreciate all the answers!
<script>
document.getElementById("confirm-details").addEventListener("click", function(){
document.getElementById("BookingName").innerHTML = document.getElementById("InputName").value;
document.getElementById("BookingEmail").innerHTML = document.getElementById("InputEmail").value;
document.getElementById("BookingPhone").innerHTML = document.getElementById("InputPhone").value;
document.getElementById("InputDay").innerHTML = document.getElementById("BookingDay").value;
document.getElementById("InputTime").innerHTML = document.getElementById("BookingTime").value;
document.getElementById("InputService").innerHTML = document.getElementById("BookingService").value;
document.getElementById("InputExtra").innerHTML = document.getElementById("BookingExtra").value;
});
</script>
Here is what I believe you are trying to accomplish:
function confirmDetails() {
// Set variable to form input
var phone = document.getElementById("inputPhone").value;
var confirmMsg = 'is ' + phone + ' correct?' + '<br> <input type="button" value="Yes" onclick="confirmed()"> ';
// Change text element to variable
document.getElementById("bookingPhone").innerHTML = confirmMsg;
};
function confirmed(){
alert('confirmed');
}
<input id="inputPhone" type="text" placeholder="input here">
<input type="button" onclick="confirmDetails()" value="Submit">
<br>
<span id="bookingPhone"></span>
When the button is clicked, it runs the function confirmDetails and sets the variable phone to the user's input. I set variable confirmMsg to the confirm message which reads back the user's input. I used a span with a unique ID and sent the variable confirmMsg to it.
I put the confirm message into a variable to make it more versatile, should you need it elsewhere.

Passing the value of a button into a text field

I'm having some trouble with getting Javascript to pass a value (which is stored in local storage) into a textfield. Ideally, I'd like for someone to be able to click the 'apply here' button on one page, have the job number stored in local storage and then have it auto-populate the job number field on my application page with the job number.
This is what I've got so far, I have a feeling that I haven't assigned things correctly.
html (on submit page)
<p>
<form id="applyjob1" action="enquire.html" method="get">
<input type="submit" id="job1" value="Apply for Job" />
</form>
</p>
html (field I'm trying to put data into)
Job Reference Number <input required="required" id="jobNo" name="jobno" type="text" /> </br />
Javascript
window.onload = function init() {
var jobID = document.getElementById("job"); /*button name */
jobID.onsubmit = passJob; /*executes passJob function */
}
function passJob(){
var jobSubmit = localstorage.jobID("1984"); /*assigns localstorage*/
if (jobSubmit != undefined){
document.getElementById("jobNo").value = localstorage.jobID;
}
I think this code would work for your fuction.
function passJob(){
localStorage.setItem("jobID", "1984");
if (localStorage.jobID != undefined) {
document.getElementById("jobNo").value = localStorage.jobID;
}
}
You are assigning the jobSubmit wrongly. To set item, use localStorage.setItem('key', value). Note the casing as it matters.
So basically you should do
var jobSubmit = localStorage.setItem(,"jobID", "1984"); // assigns jobSubmit
And I don't see any element with id="job"

How can I get these two javascript codes to work together?

I made a form using html.
At first I had it really simple. My input was amount, which a user would enter. I then made javascript code to calculate a dynamic price based on the user's amount input. The code is as follows:
<input class="typeahead" type="text" placeholder="Amount" name="Gift-Card Amount"/>
The javascript:
jQuery("input[name='Gift-Card Amount']").change(function () {
if (isNaN(parseFloat(this.value)) || !isFinite(this.value)) {
jQuery(this).val('');
return false;
}
var calc = parseFloat(this.value) * 0.95;
jQuery(this).parents("form").find("input[name='price']").val(calc);
});
The calculation is a constant 0.95. So I added a new input. Store name. So the user could enter the store name. The amount:
<input class="stores typeahead" type="text" placeholder="Stores" name="name"/>
And I want price to change based on both store name and amount. So I created this object:
var stores = {
"McDonalds" : .90,
"Target" : .92,
}
var storeName = jQuery(this).parents("form").find("input[name='name']").val();
console.log(stores[storeName]);
So that instead of a constant 0.95, that value can be replaced with preset values based on the store name entered. I don't know how to get those two to work together. Meaning, how do I recode the first javascript to recornize the var store values instead of 0.95?
jQuery("input[name='Gift-Card Amount']").change(function () {
var amount = parseFloat(this.value);
if (isNaN(amount) || !isFinite(amount)) {
jQuery(this).val('');
return false;
}
var storeName = jQuery(this).parents("form").find("input[name='name']").val();
if (storeName in stores) {
var calc = amount * stores[storeName];
jQuery(this).parents("form").find("input[name='price']").val(calc);
}
});
I also suggest that you change Stores from a text input to <select>. That way, you don't depend on the user spelling the store correctly, including capitalization.
<select name="name" class="storeName">
<option value="">Please select a store</option>
<option value=".90">McDonalds</option>
<option value=".92">Target</option>
</select>
Then you can use
var calc = parseFloat(jQuery(this).parents("form").find(".storeName").val());
I would do it like the following:
function calcPrice(element) {
// Use the element that called the listener to find the form
var form = element.form;
// Access form controls as named properties of the form
var amt = form["Gift-Card Amount"].value;
// Don't clear the value if it's not suitable, it's annoying
// Let the user fix it themselves
if (parseFloat(amt) != amt) {
alert("Gift card amount is not a suitable value")
}
// Set the price
form.price.value = amt * form.store.value;
}
</script>
Sample form, which has all the store values. This way, you can have a fallback where the server gets all relevant values, you aren't dependent on client side calculations..
<form>
Store:
<select name="store" onchange="calcPrice(this)">
<option value="0.90">McDonalds
<option value="0.92">Target
</select>
<br>
Gift card amount:
<input name="Gift-Card Amount" onchange="calcPrice(this)">
Price:
<input name="price" readonly>
</form>
write a little function that may return the correct value
function retrieveStoreValue(store){
return stores[store];
} // be sure stores is defined before the first call of this one
and in your change function call it
var storeName = jQuery(this).parents("form").find("input[name='name']").val();
var calc = parseFloat(this.value) * (retrieveStoreValue(storeName) );

Turn HTML Form Input into JavaScript Variable

I am new to HTML forms and I was wondering how I can easily (or not) change it's input to a JavaScript variable. Here is my code:
<head>
<title>Begin</title>
<link type="text/css" rel="stylesheet" href="begin.css"/>
</head>
<body>
<form action="begin-create-done.html" method="get">
First Name: <input type="text" name="firstname">
<br>
Last Name: <input type="text" name="lastname">
<br>
<br>
New Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pass">
<br>
Repeat Password: <input type="password" name="rpass">
<input type="submit" value="Submit">
</form>
</body>
</html>
I want each part of the form (e.x. First Name, Last Name, New Username, etc.) to be it's own JavaScript variable. Thank you very much!
Accessing HTML input elements from JavaScript
Assuming you don't have other elements with same names, you can access input values from JavaScript by name as follows:
var firstName = document.getElementsByName("firstname")[0].value;
You now have the value from firstname field in JavaScript variable called firstName. Just keep repeating and you got the other input fields too. You can then proceed and wrap these statements to a function and call it when input data changes. For example:
function formChanged() {
var firstName = ...
var lastName = ...
}
Now register this function call to change / keyup events and you have a function that monitors changing form values:
<input type="text" name="firstname" onkeyup="formChanged()" onchange="formChanged()"/>
Should you prefer a more structured approach, or if you have more than one form on the page, you could:
Create an object that will hold all form values and update them. After that you could simply access them with formValues.inputName.
Store your default values in an array (in the same order as your inputs).
Execute a function that will take care of outputting the default values & updating the object when the values are changed. It takes the form (selected by Id, Class, whatever) and an array of default values as parameters.
// create the object that will hold the input values
var formValues = {};
// store code in the function for a more 'modular' approach
function inputObj(formNR, defaultValues) { // where defaultValues is an array
var inputs = formNR.getElementsByTagName('input');
for ( var i = 0; i < inputs.length; i++) {
if(inputs[i].type === 'text' || inputs[i].type === 'password') {
formValues[inputs[i].name] = defaultValues[i]; // store default in object
}
inputs[i].value = defaultValues[i]; // output default in input
inputs[i].addEventListener('keyup', function() { // update object on change
formValues[this.name] = this.value;
}, false);
}
}
// build a little array with the defaultValues for each input
var defValues =['defaultFirstName','defaultLastName','defaultUser',
'defaultPass','defaultPass'];
// this will push all inputs from the given form in the formValues object.
inputObj(document.forms[0], defValues);
// Access the values like this, eg.
console.log(formValues.firstname); // will return 'defaultFirstName'
See it in action here. Or with CodeView. Note: The code in the example has some additions to show the object's values on the page.
Try to first create a function that grabs the value from the input field:
<script>
function XX()
{
var first2 = document.getElementById("firstname").value;
}
</script>
Then you have to fire it up when the input changes with onchange:
FirstName: <input type="text" id="firstname" name="firstname" onchange="XX()">

Categories