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>
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 would just like to know is it possible to change the input automatically to capitalized on a certain input field where the user entered a value with Caps Lock on.
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps On = TEST NAME
Expected: Test Name
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps Off = test name
Default: Test Name
I know some Names looks like Reader Van der Bank where not all the name parts are capitalized, but still would like to know if its possible. Thanks
Alternative : Think i might be using a php function to transform everything to lowercase and then capitalized.
Here is a javascript function to do that, if there is no CSS solution for it.
var id = document.getElementById("test");
function change() {
var arr = id.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
id.value = arr.join(" ");
}
id.addEventListener("change", change);
id.addEventListener("keyup", change);
<input placeholder="Brand Name" id="test" type="text" />
For multiple elements with class test
var elements = document.getElementsByClassName("test");
function change() {
var arr = this.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
this.value = arr.join(" ");
}
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener("change", change);
elements[i].addEventListener("keyup", change);
}
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
Do you want to enter all the text capitalized in the input? then u can use text-transform:uppercase in css and if u want to change it while typing you can use toUpperCase() on keyup of that input.
style="text-transform: capitalize"
(Question was edited. New Answer.)
Give your input an id, for this example let's say it's called "theInputId".
Then add an onkeypress event to it also and call the function script I've listed below.
<input placeholder="Brand Name" style="text-transform: capitalized"
type="text" id="theInputId" onkeypress="capsLock(event)">
<script>
//Script to check if Caps Lock is on.
function capLock(e){
kc = e.keyCode?e.keyCode:e.which;
sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)){
document.getElementById('theInputId').style.textTransform = 'lowercase'
document.getElementById('theInputId').style.textTransform = 'capitalize'
}
}
</script>
I am trying to change/set a value using javascript.
From what I have currently created this works for a piece of text in tags going by the id: title.
It works like this:
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = myNewTitle;
}
<h1 id="title">test</h1>
<input type="text" id="myTextField" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
Now what I want to set is a value inside here:
Voornaam + Achternaam:<input type="text" name="firstname" value="" />
Which is basically supposed to be a firstname.
I want the value to be set, using the method I was already using for my tag.
However when I give it an id like so:
Voornaam + Achternaam:<input type="text" id="firstname" value="" />
And also change my function change to that id instead of title, it doesn't change or set the value inside the firstname field.
could anybody help me out?
While I don't understand why you want one input to update another , if you want to change the value of an input field you must use .value instead of .innerHTML
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('firstname');
title.value = myNewTitle;
}
<h1 id="title">test</h1>
Voornaam + Achternaam:<input type="text" id="firstname" value="" />
<br/><br/>
<input type="text" id="myTextField" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
You set the value attribute on an element with the value key:
var firstnameInput = document.getElementById('firstname');
firstnameInput.value = 'Firstname value';
You need to do this:
Use firstname.value = myNewTitle; instead of innerHTML.
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var firstname = document.getElementById('firstname');
firstname.value = myNewTitle;
}
<h1 id="title">test</h1>
<input type="text" id="myTextField" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
Voornaam + Achternaam:<input type="text" id="firstname" value = ""/>
I have 8 different text fields in my form, it's a part of customer bill.
Here it is
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty">
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation">
......
up to 8
From this I want to show the sum of all the values as total value
<span>Total extra cost:1678</span>
It should be changed when the values of any text field is changed, so how can I do it perfectly using keyup event?
UPDATE
I have attached an onkeyup event to each textfield
`onkeyup="findSum(this.value)"'
and i am using a global array for store the input values var extras=[]
function findSum(value)
{
if(value!=''){
console.log(value);
extras.push(parseInt(value));
if(extras!='')
$('#extratotal').text(extras.reduce(getSum));
else $('#extratotal').text('0');
}
}
But its not worked well
You can get SUM of all inputs that have form-control class on keyup event like this:
$('input.form-control').on('keyup',function() {
var total = 0;
$('input.form-control').each(function(){
if (this.value == ''){
total += parseInt(0);
}else{
total += parseInt(this.value);
}
});
$('#total').val(total);
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty" >
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation" >
<input type="text" name="other" class="form-control" placeholder="other" >
Total extra cost: <input id="total" >
You can use the target.value property of the event passed to the key listener - this will give you the value of the input field:
document.addEventListener('input', 'keyup', function(e) {
// use e.target.value here
}
Just add this to a running total and update the text inside the listener function.
I have defined in JavaScript instead of jQuery. Try it..
<script>
function sum()
{
var sum = 0;
var array_field = document.getElementsByClassName('sum_field');
for(var i=0; i<array_field.length; i++)
{
var value = Number(array_field[i].value);
if (!isNaN(value)) sum += value;
}
document.getElementById("total").innerHTML = sum;
}
</script>
<body>
<input type="text" name="txtcustomduty" class="form-control sum_field" placeholder="Customs Duty" onkeyup="sum()">
<input type="text" name="txtlcltranspotation" class="form-control sum_field" placeholder="Local Transportation" onkeyup="sum()">
<p>Total:<span id="total">0</span></p>
</body>
I currently have this html code:
Add More Field
<div id="addmore">
<ul class="jcform" id="countme">
<li><input id="name" class="form-control" name="cname[]" type="text" value=""/></li>
<li><input id="score" class="form-control" name="cscore[]" type="text" value=""/></li>
</ul>
</div>
Total: <div id="displaytotalscore"></div>
Below is my javascript:
function removeme(numm) {
document.getElementById('remove'+numm+'').remove();
}
function addmore() {
var top_level_div = document.getElementById('addmore');
var count = top_level_div.getElementsByTagName('ul').length;
var ul = document.createElement('ul');
ul.className = 'jcform';
ul.id = 'remove' + count;
var tbl1 = '<li><input class="form-control" id="field1" name="cname[]" type="text"
value=""/></li>
<li><input class="form-control" id="fieldpoints1" name="cpoints[]"
type="text" value=""/></li>
<li><a href="#" class="btn btn-danger" onclick="removeme(' + count + ')">
Removed</a></li>';
ul.innerHTML = tbl1;
document.getElementById('addmore').appendChild(ul)
}
What i want to achieve is, when a user enters values in the text fields id="score", i want to display the total sum in the div id="displaytotalscore". I am not sure how to use onchange event here.
Ok here's the jsfiddle link http://jsfiddle.net/41fw2c4x/
document.querySelector("#score").addEventListener("change", function(){
document.querySelector("#displaytotalscore").textContent = this.value;
}, false);
Add More Field
<ul class="jcform" id="countme">
<li><input id="name" class="form-control" name="cname[]" type="text" value=""/></li>
<li><input id="score" class="form-control" name="cscore[]" type="text" value=""/></li>
</ul>
Total: <div id="displaytotalscore"></div>
This shows the basic working of the onchange event. User fills in a score in the input with id score. When this loses focus (blurs) it will invoke the onchange event setting the score to the div using the property textContent.
Updated with your fiddle:
http://jsfiddle.net/41fw2c4x/2/
function addmore() {
var top_level_div = document.getElementById('addmore');
var count = top_level_div.getElementsByTagName('ul').length;
var ul = document.createElement('ul');
ul.className = 'jcform';
ul.id = 'remove' + count;
var tbl1 = '<li>Name <input class="form-control" id="field1" name="cname[]" type="text" value=""/></li> <li>Score <input class="form-control" id="fieldpoints1" name="cpoints[]" type="text" value=""/></li><li>Removed</li>';
ul.innerHTML = tbl1;
document.getElementById('addmore').appendChild(ul)
}
//my solution
document.querySelector("#addmore").addEventListener("keyup", function(e){
if (e.target && e.target.tagName == "INPUT" && e.target.name == "cpoints[]")
{
updateScore();
}
}, false);
function updateScore()
{
var score = 0;
Array.prototype.map.call(document.querySelectorAll("input[name='cpoints[]']"), function(element){
score += !isNaN(parseInt(element.value)) ? parseInt(element.value) : 0; //when not a digit add 0, or ignore.
});
document.querySelector("#displaytotalscore").textContent = score;
}
function removeme(numm) {
document.getElementById('remove' + numm + '').parentElement.removeChild(document.getElementById('remove' + numm + ''));
updateScore();
}
//solution end
Add More Field
<div id="addmore">
<ul class="jcform" id="countme">
<li>Name
<input id="name" class="form-control" name="cname[]" type="text" value="" />
</li>
<li>Score
<input id="score" class="form-control" name="cpoints[]" type="text" value="" />
</li>
</ul>
</div>Total:
<div id="displaytotalscore"></div>
This adds an keyup event to the main div (addmore). Every time it detect an input element with the name cpoints[], it will iterate over all inputs with that name. Sum the total amount and display it in the div. It ignores values other than numbers by assigning the value 0. It checks if something is a number with the isNaN method.
Why did I switch to the keyup event? It allows me to use only one event, instead of adding an onchange event for every input. Why not set an onchange event on the div then? div don't support onchange events, so we need a different approach, in this case the keyup.