I have an HTML form and I'm wondering how I can set that info when submitted to the variables in my js file.
HTML
<input id="column-left" type="text" name="first-name" placeholder="First Name"/>
<input id="column-right" type="text" name="last-name" placeholder="Last Name"/>
<input id="input-field" maxlength="16" type="text" name="number" placeholder="Card Number"/>
<input id="column-left" maxlength="4" type="text" name="expiry" placeholder="MM / YY"/>
<input id="column-right" maxlength="3" type="text" name="cvc" placeholder="CCV"/>
(Leaving out unimportant info)
JS
var order_info = {name: "your name", // your first and last name
email: "your#email.com", // your email
phone: "5555555555", // your phone number
address1: "123 street lane", // your street address
address2: "apartment 1", // leave blank if you dont have one
zip_code: "00000", // your zip code
city: "New York", // city
state_code: "NY", // state code, if you dont know this then look it up son
country: "USA" // only two options, "USA" or "CANADA"
};
I need to set the info from the form into these fields.
One of many ways to get values from html form tag to Javascript object.
document.querySelector("#myForm").addEventListener("keyup", function(){
var data = {};
var inputs = document.querySelectorAll('input');
inputs.forEach(input => {
data[input.name] = input.value;
});
document.querySelector("#text").innerText = JSON.stringify(data);
});
document.querySelector("#myForm").dispatchEvent(new Event('keyup'));
<form id="myForm">
<input value="Niklesh" type="text" name="first_name" placeholder="First Name"/>
<input value="Raut" type="text" name="last_name" placeholder="First Name"/>
<input value="" type="text" name="email" placeholder="Email"/>
<div id='text'></div>
</form>
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var card = document.getElementById("card").value;
var expire = document.getElementById("expire").value;
var cvc = document.getElementById("cvc").value;
var order_info = {
fname: fname ? fname : '',
lname: lname ? lname : '',
card: card ? card : '',
expire: expire ? expire : '',
cvc: cvc ? cvc: ''
}
console.log(order_info);
<input id="fname" type="text" name="first-name" value="sourav" placeholder="First Name"/>
<input id="lname" type="text" name="last-name" value="singh" placeholder="Last Name"/>
<input id="card" maxlength="16" type="text" name="number" value="" placeholder="Card Number"/>
<input id="expire" maxlength="4" type="text" name="expiry" value="08/12" placeholder="MM / YY"/>
<input id="cvc" maxlength="3" type="text" name="cvc" value="111" placeholder="CCV"/>
First you should define a unique ID to each input you have, then get the value of this ID using javascript document.getElementById('ID').value or using jQuery $('ID').val().
Second part, you must match your number of inputs with your array.
Now you have an array of data, do what ever you want to do with it.
document.getElementById("save").addEventListener("click", function() {
var order_info = {
firstName: document.getElementById('first-name').value,
lastName: document.getElementById('last-name').value,
number: document.getElementById('number').value,
expiry: document.getElementById('expiry').value,
cvc: document.getElementById('cvc').value,
};
console.log(order_info);
});
<input id="first-name" type="text" name="first-name" placeholder="First Name"/>
<input id="last-name" type="text" name="last-name" placeholder="Last Name"/>
<input id="number" maxlength="16" type="text" name="number" placeholder="Card Number"/>
<input id="expiry" maxlength="4" type="text" name="expiry" placeholder="MM / YY"/>
<input id="cvc" maxlength="3" type="text" name="cvc" placeholder="CCV"/>
<button id="save">Save Data</button>
if you want to serialise data;
var order_info = $('form').serializeArray();
if you want to use formdata :
var fd = new FormData();
var order_info = $('form').serializeArray();
$.each(order_info,function(key,input){
fd.append(input.name,input.value);
});
Using the DOM (Document Object Model) you can access the values of the HTML components.
For example, given your code, you can lookup the element by its "id":
var lastname = document.getElementById("column-right");
var cardnumber = document.getElementById("input-field");
... etc
You can also lookup the element by using the value of its "name" attribute:
var lastname = document.getElementsByName("last-name");
var cardnumber = document.getElementsByName("number");
Tip: You normally do this when the page is loaded (event "onload") and if the values are received by the same page, it needs to implement typically the scenario of the first load as well (where the values are null, not initialized).
Javascript references:
https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
https://www.w3schools.com/jsref/met_document_getelementbyid.asp
You can use JQuery .serializeArray() method to do so.
like this:
var x = $("form").serializeArray();
You should get Key:Value pairs of all the text fields and their values by doing so.
Related
This simple form is part of a larger web app I have created. Both the required attributes and the pattern attributes only work intermittently. Changing the event listener to "submit" rather than "click" makes the form validation work properly, but then I get a blank page when I submit with the proper input formatting.
var v = "userForm"
document.getElementById("clockIn").addEventListener("click", addLine); //CHANGE TO CLICK FOR WORKING PAGE BUT PATTERN WONT WORK
function addLine() {
//e.preventDefault();
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var jobNumber = document.getElementById("jnum").value;
var process = document.querySelector('input[name="operation"]:checked').value;
var comment = document.getElementById("comment").value;
var timeIn = new Date().toLocaleString();
var info = [firstName, lastName, jobNumber, process, timeIn, comment];
google.script.run.addEntry(info);
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("jnum").value = "";
document.getElementById("comment").value = "";
document.querySelector('input[name="operation"]:checked').checked = false;
alert("Submitted");
}
function addEntry(info) {
var ssid = "1E81r5Xy**********************W1o4Q";
var ss = SpreadsheetApp.openById(ssid);
var oj = ss.getSheetByName("Open Jobs");
var FileIterator = DriveApp.getFilesByName("Drawings & Links");
while (FileIterator.hasNext()) {
var file = FileIterator.next();
if (file.getName() == "Drawings & Links") {
// var Sheet = SpreadsheetApp.open(file);
var dlid = file.getId();
}
}
var drawingLinks = SpreadsheetApp.openById(dlid);
var dl = drawingLinks.getSheetByName("Sheet1");
Logger.log(dlid)
oj.appendRow(info);
}
<form id="inputForm">
<h2 class="subHead">
Enter Basic Information
</h2>
<label for="fname" class="form">First name:</label><br><br>
<input type="text" id="fname" name="fname" size="25" style="font-size:25px;" placeholder="John" required><br><br>
<label for="lname" class="form">Last name:</label><br><br>
<input type="text" id="lname" name="lname" size="25" style="font-size:25px;" placeholder="Doe" required><br><br>
<label for="jnum" class="form">Job number:</label><br><br>
<input type="text" id="jnum" name="jnum" size="25" style="font-size:25px;" pattern="[A-Z]-[0-9]{4}" placeholder="A-1234" required><br>
<h2 class="subHead">
Select Operation
</h2>
<div>
<label for="cut" class="form">Cut</label>
<input type="radio" id="cut" name="operation" value="cut" required><br><br>
<label for="drill" class="form">Drill</label>
<input type="radio" id="drill" name="operation" value="drill" required><br><br>
<label for="fitup" class="form">Fit Up</label>
<input type="radio" id="fitup" name="operation" value="fit up" required><br><br>
<label for="weld" class="form">Weld</label>
<input type="radio" id="weld" name="operation" value="weld" required><br>
</div>
<h2 class="subHead">
Enter Comments
</h2>
<input type="text" id="comment" size="25" style="font-size:25px;" placeholder="Optional"><br>
<br>
<input type="submit" id="clockIn" class="button" value="Clock In">
</form>
Thanks for the help.
I think I have narrowed the problem down to something to do with the event listener. My thought is that when the "click" event is used, the function runs before the fields are validated by the browser. Yet, I just get a blank page if I use the "submit" event. The function "addEntry" doesn't appear to run; the logged data doesn't appear. Same goes for "addLine" when I add an alert. I have isolated the regex code and verified it works as expected.
Edit: I found that when I remove the event listener on the submit button and add an onsubmit (onsubmit="addLine()") attribute to the form, the alert in "addLine" appears. The "Submitted" alert also appears. Still a blank page after.
Your validation fails but that is outside the scope of the question as I see it since you need to check the actual values before you let it submit and probably need a preventDefault() on the form if any fail.
You get an error because you cannot filter by :checked unless you then determine if that is null OR filter it after you get the nodeList.
Here I show a couple of ways to handle the radio buttons; up to you to determine which suits you.
var v = "userForm"
document.getElementById("clockIn").addEventListener("click", addLine); //CHANGE TO CLICK FOR WORKING PAGE BUT PATTERN WONT WORK
function addLine() {
//e.preventDefault();
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var jobNumber = document.getElementById("jnum").value;
//demonstrate a few ways to hanlde the radio buttons:
const procOne = document.querySelector('input[name="operation"]:checked');
console.log(!!procOne ? procOne.value : procOne, typeof procOne); // null and object if none are checked
let processValue = procOne === null && typeof procOne === "object" ? "" : procOne.value;
// querySelectorAll to get all of them so we can filter the list
const processAll = document.querySelectorAll('input[name="operation"]');
// creates an array like object of the nodelist; then filters it for checked ones
const checkProcess = [...processAll].filter(item => item.checked);
console.log("How many?:", processAll.length);
console.log("How many checked?:", checkProcess.length);
console.log(checkProcess.length ? checkProcess.value : "nothing");
// anther way to get value:
processValue = checkProcess.length ? checkProcess.value : "nothing"
if (checkProcess.length !== 0) { //Test if something was checked
console.log(checkProcess.value); // the value of the checked.
} else {
console.log('Nothing checked'); // nothing was checked.
}
var comment = document.getElementById("comment").value;
var timeIn = new Date().toLocaleString();
let process = processValue;
var info = [firstName, lastName, jobNumber, process, timeIn, comment];
//ccommented out as google is not defined
//google.script.run.addEntry(info);
// hitting the DOM again is not a great thing here but left as not part of the question/issue
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("jnum").value = "";
document.getElementById("comment").value = "";
// cannot filter by :checked if none are so check first and set to false
if (procOne != null) procOne.checked = false;
alert("Submitted");
}
function addEntry(info) {
var ssid = "1E81r5Xy**********************W1o4Q";
var ss = SpreadsheetApp.openById(ssid);
var oj = ss.getSheetByName("Open Jobs");
var FileIterator = DriveApp.getFilesByName("Drawings & Links");
while (FileIterator.hasNext()) {
var file = FileIterator.next();
if (file.getName() == "Drawings & Links") {
// var Sheet = SpreadsheetApp.open(file);
var dlid = file.getId();
}
}
var drawingLinks = SpreadsheetApp.openById(dlid);
var dl = drawingLinks.getSheetByName("Sheet1");
Logger.log(dlid)
oj.appendRow(info);
}
<form id="inputForm">
<h2 class="subHead">
Enter Basic Information
</h2>
<label for="fname" class="form">First name:</label><br><br>
<input type="text" id="fname" name="fname" size="25" style="font-size:25px;" placeholder="John" required><br><br>
<label for="lname" class="form">Last name:</label><br><br>
<input type="text" id="lname" name="lname" size="25" style="font-size:25px;" placeholder="Doe" required><br><br>
<label for="jnum" class="form">Job number:</label><br><br>
<input type="text" id="jnum" name="jnum" size="25" style="font-size:25px;" pattern="[A-Z]-[0-9]{4}" placeholder="A-1234" required><br>
<h2 class="subHead">
Select Operation
</h2>
<div>
<label for="cut" class="form">Cut</label>
<input type="radio" id="cut" name="operation" value="cut" required><br><br>
<label for="drill" class="form">Drill</label>
<input type="radio" id="drill" name="operation" value="drill" required><br><br>
<label for="fitup" class="form">Fit Up</label>
<input type="radio" id="fitup" name="operation" value="fit up" required><br><br>
<label for="weld" class="form">Weld</label>
<input type="radio" id="weld" name="operation" value="weld" required><br>
</div>
<h2 class="subHead">
Enter Comments
</h2>
<input type="text" id="comment" size="25" style="font-size:25px;" placeholder="Optional"><br>
<br>
<input type="submit" id="clockIn" class="button" value="Clock In">
</form>
I'm a beginner and I'm now stuck trying to figure out two things for the below code:
How do I code so that each of the send buttons only connects to its own input field?
How do I code so that each new text input overwrites the previous?
My code:
<h1>Data input</h1>
<input type="text" placeholder="Last name" id="inputField1" name="lastName" required>
<input type="button" value="Send" id="myButton1">
<br>
<br>
<input type="text" placeholder="First name" id="inputField2" name="firstName" required>
<input type="button" value="Send" id="myButton2">
<br>
<br>
<p id="lastName">Last name</p>
<p id="firstName">First name</p>
<script>
var b1=document.getElementById("myButton1")
b1.addEventListener("click", handleClick);
var b2=document.getElementById("myButton2")
b2.addEventListener("click", handleClick);
function handleClick(){
var i=document.getElementById("inputField1");
var iValue=i.value;
var d=document.getElementById("lastName");
var oldText=d.innerText;
var newText=oldText+"\n"+iValue;
d.innerText=newText;
var k=document.getElementById("inputField2");
var kValue=k.value;
var f=document.getElementById("firstName");
var oldText=f.innerText;
var newText=oldText+"\n"+kValue;
f.innerText=newText;
}
Here is a solution that sends a 1 or a 2 to the handleClick function as a parameter depending on which button you click. It then gets the value of the input that matches the number, checks to make see if it is empty, and outputs the name to the correct paragraph if it isn't and an error message if it is. Let me know if you have any problems with it.
var b1 = document.getElementById("myButton1");
b1.addEventListener("click", () => handleClick("1"));
var b2 = document.getElementById("myButton2");
b2.addEventListener("click", () => handleClick("2"));
function handleClick(iNum){
var i = document.getElementById("inputField" + iNum);
var iValue = i.value;
var d = document.getElementById("name" + iNum);
if (iValue != "") {
var pText = (iNum == "1" ? "Last" : "First");
var newText = pText + " name: " + iValue;
d.textContent = newText;
} else {
d.textContent = "Please enter a name!";
}
}
<h1>Data input</h1>
<input type="text" placeholder="Last name" id="inputField1" name="lastName" required>
<input type="button" value="Send" id="myButton1">
<br>
<br>
<input type="text" placeholder="First name" id="inputField2" name="firstName" required>
<input type="button" value="Send" id="myButton2">
<br>
<br>
<p id="name1"></p>
<p id="name2"></p>
Not really sure what's going on here, but usually you have to access the input field via the event: event.target.value (just put event as a parameter)
I'm attempting to build an object of the input values in the form below, then log that object to the console; but it the values are not being retrieved properly.
What is wrong with my code?
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.getElementsByClassName('personName').value;
var personEmail = document.getElementsByClassName('personEmail').value;
var personMessage = document.getElementsByClassName('personMessage').value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" class="personName" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success" id="inputHorizontalSuccess" class="personEmail" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" class="personMessage" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
You have multiple Ids:
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" id="personName" placeholder="Name">
You can either remove inputHorizontalSuccess.
Or add a name and get value from it instead, incase you must have inputHorizontalSuccess.
This should do it:
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess1" name="personName" placeholder="Name">
<input type="email" class="form-control form-control-success" id="inputHorizontalSuccess2" name="personEmail" placeholder="name#example.com">
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess3" name="personMessage" placeholder="Your Message">
var personName = document.querySelector('[name="personName"]').value;
var personEmail = document.querySelector('[name="personEmail"]').value;
var personMessage = document.querySelector('[name="personMessage"]').value;
I recommend you read this question on how to get value from the DOM.
How do I get the value of text input field using JavaScript?
Only the first class attribute in an element definition is applied. This means that when you write the following:
<input type="text" class="form-control form-control-success" ... class="personName" placeholder="Name">
The later "class" attribute will not apply. This means that the element cannot be selected by this class.
Document.getElementsByClassName returns a live HTMLCollection even if there is only a single element. This means that when you write:
var personName = document.getElementsByClassName('personName').value;
There is no value property in the live HTMLCollection returned by the call to Document.getElementsByClassName, so it will return undefined.
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.getElementsByClassName('personName')[0].value;
var personEmail = document.getElementsByClassName('personEmail')[0].value;
var personMessage = document.getElementsByClassName('personMessage')[0].value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success personName" id="inputHorizontalSuccess" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success personEmail" id="inputHorizontalSuccess" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success personMessage" id="inputHorizontalSuccess" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
However, you should probably use ID's instead of classes and Element#querySelector, to avoid conflict:
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.querySelector('#personName').value;
var personEmail = document.querySelector('#personEmail').value;
var personMessage = document.querySelector('#personMessage').value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success" id="personName" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success" id="personEmail" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success" id="personMessage" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
I am developing a task management system in that i am having the age field in registration form i am having doubt about how to update the field automatically when i click.
my script is
<script>
var a = document.age1.dob.value;
age = a.getFullYear();
var curr = new Date();
year = curr.getFullYear();
var age1 = year - age;
</script>
i calculated the age and stored it in age1 variable.
<form id="form2" action="#" method="post" name="age1">
<h4><b>Register here</b></h4>
<b>Name</b>: <input type="text" name="name" required="required" placeholder="Your name" pattern="[a-zA-Z0-9\s]+"><br><br>
<b>E-mail</b>: <input type="email" name="email" required="required" placeholder="someone#example.com" pattern="[a-z0-9._+%-]+#[a-z0-9.-]+\.[a-z]{2,4}$"><br><br>
<b>Password</b>: <input type="password" name="password" required="required"><br><br>
<b>DOB</b>: <input type="text" name="dob" required placeholder="dd/mm/yyyy" pattern="^[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}$"><br><br>
<b>Age</b>: <input type="text" name="age" id="age2"><br><br>
<b>Address</b>: <textarea name="address" rows="6" cols="30"></textarea>
<button id="butr" type="submit" class="btn btn-warning">Signup</button>
After i input my DOB in the registration form and click the age field i want the calculated age that i stored it in age1 variable to automatically update the value in age field that i have it in my registration form
Add an onchange function to dob field
<input type="text" onchange="ageCalculation()" name="dob">
Add this code in your <script>
function ageCalculation(){
if(document.age1.dob.value!==""){
var a = document.age1.dob.value;
a=new Date(a);
age = a.getFullYear();
var curr = new Date();
year = curr.getFullYear();
var age1 = year - age;
document.age1.age.value=age1;
}
}
Okay, so I have a form which adds an item to a list of items and does calculations with it, but every new item thats added is done on the users side before being submitted to the server for verification and updating of database. Now, I've looked at other answers and couldnt really get an answer. If the user adds a new item and enter a quantity and rate it should calculate the amount automatically, how would one extract the unique ID identifier to change the value of the amount? The code below and in this case the unique identifier is 19786868. The length of this identifier is always different and their is no unique pattern, the length and value is generated by a random command.
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
How would I extract this unique identifier with the OnChange command in JavaScript to calculate the amount value?
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
var id = el.id.replace(/\D+/g,"");
console.log( id ); // "19786868"
});
so basically use a this.id.replace(/\D+/g,"") where all non Digit \D gets replaced by ""
Here's an example using the input event:
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
el.addEventListener("input", function() {
var id = this.id.replace(/\D+/g,"");
alert( id );
}, false)
});
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_123_foobar" />
Take note that: asd_123_foo_9 will return 1239 as result so make sure to always have asd_123_foo as ID value
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" onchange="extractId(event);"/>
And in javascript :
function extractId(event) {
var elem = event.target;
var myArr = elem.id.split('_');
var yourUnique_id = myArr[3];
}
To be able to respond to newly added input controls, you need to capture the change event at some parent element, otherwise you will not trap the change on newly added elements.
Here is some code that handles the change event on the document. As this event bubbles up, it will eventually get there, so we can respond to it:
For extracting the number from the input's id, we can use a regular expression:
document.onchange = function(e) {
var match = e.target.id.match(/^(list_item_attributes_.*?_)(rate|quantity)$/);
if (!match) return; // not rate or quantity
// read rate and quantity for same ID number:
var rate = +document.querySelector('#' + match[1] + 'rate').value;
var quantity = +document.querySelector('#' + match[1] + 'quantity').value;
// write product as amount:
document.querySelector('#' + match[1] + 'amount').value = rate*quantity;
}
Quantity: <input class="form-control" type="text" id="list_item_attributes_19786868_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_19786868_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_19786868_amount" /><br>
<p>
Quantity: <input class="form-control" type="text" id="list_item_attributes_14981684_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_14981684_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_14981684_amount" /><br>
As you have asked to respond to the change event, I have kept it that way, but you might be interested to use the input event instead, which will trigger as soon as any character changes in an input.
The above sample does not protect the amount fields from input. You should probably do something about that, because users could just overwrite the calculated result.
document.querySelector(".my-form").addEventListener("change", function(e) {
var changed = e.target;
var matchedId = changed.id.match(/^(list_item_attributes_[^_]*)_/);
if (!matchedId) {
// this isn't one of the relevant fields
return;
}
var uniquePrefix = matchedId[1];
var quantity = document.querySelector("#" + uniquePrefix + "_quantity");
var rate = document.querySelector("#" + uniquePrefix + "_rate");
var amount = document.querySelector("#" + uniquePrefix + "_amount");
var newVal = quantity.value * rate.value;
if (isNaN(quantity.value) || isNaN(rate.value) || isNaN(newVal)) {
amount.value = "";
} else {
amount.value = newVal;
}
});
<form class="my-form">
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</form>
If the user adds a new item and enter a quantity and rate it should
calculate the amount automatically, how would one extract the unique
ID identifier to change the value of the amount?
You can use input event; for loop; attribute contains selector [attributeName*=containsString], .nextElementSibling, .previousElementSibling, to sum values of id containing "quantity" and id containing "rate" and set result at id containing "amount"
function calculate() {
this.parentElement.querySelector("[id*=amount]")
.value = +this.value
+ +(/quantity/.test(this.id)
? this.nextElementSibling
: this.previousElementSibling
).value
}
var elems = document.querySelectorAll("[id*=quantity], [id*=rate]");
for (var i = 0; i < elems.length; i++) {
calculate.call(elems[i]); elems[i].oninput = calculate;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" value="1" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" value="2" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</div>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786867_quantity" value="3" />
<input class="form-control" type="text" id="list_item_attributes_19786867_rate" value="4" />
<input class="form-control" type="text" id="list_item_attributes_19786867_amount" />
</div>