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>
Related
Here is my code i want to append data based on all three textbox if textbox value is 2 and textbox2's value is 3 and textbox3's value is 1 the The result will be 2 apple 3banans and 1 cherry and user can also remove items with textbox value
I have tried to make this code but it is removing all items could you please help me to solve this problem
$(".change_qty").change(function(){
var total = $(this).val();
var oldLength = $(".box > span").length;
var change = total - oldLength;
var data_text= $(this).data("text");
if (change > 0) {
for (i = 0; i < change; i++) {
$(".box").append(`<span >${data_text}<br /></span>`);
}
}
else {
change = Math.abs(change)
$( ".box > span" ).each(function( index ) {
$(this).remove();
if (index == (change -1)) {
return false;
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-control input-sm change_qty" type="number" data-text="apple">
<input class="form-control input-sm change_qty" type="number" data-text="bananas">
<input class="form-control input-sm change_qty" type="number" data-text="cherry">
<div class="box" ></div>
$(".box > span").length does not regard your different input types. It might be easier to clear everything and recreate the whole output on change. That way the entries also keep the order of input.
$(".change_qty").change(function(){
//REM: Remove all entries
$(".box").empty();
//REM: Recreate all entries
$(".change_qty").each(function(){
let tThis = $(this);
let tText = tThis.data('text');
let tQuantity = Math.abs(tThis.val());
//REM: Append quantity of entries to .box
for(let i=0, j=tQuantity; i<j; i++){
$(".box").append(`<span >${tText}<br /></span>`)
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control input-sm change_qty" type="number" data-text="apple">
<input class="form-control input-sm change_qty" type="number" data-text="bananas">
<input class="form-control input-sm change_qty" type="number" data-text="cherry">
<div class="box" ></div>
Please help me figure out why only the last input id gets its value added to the input id= #attr3 with keyup.
I need both inputs in the div to have their values put into the input outside the div separated with a comma(,). i made a fiddle https://jsfiddle.net/dc6v6gjd/1/. Thanks
<div id ="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attr3" name="username" value="">
$(document).ready(function () {
var text = $("#candy :input").map(function () {
return this.id;
}).get();
var attr = [];
for (i=0; i<text.length; i++) {
attr.push('#'+ text[i]);
}
var mat = attr.join(", ");
$(mat).keyup(function(){
update();
function update() {
attr.forEach(function(index, i){
// alert(i);
$("#attr3").val( $(attr[i]).val() + "," );
});
}
});
});
The reason is you're overriding the value of attr3 on each iteration of forEach. You could instead use join to get the value.
e.g.
function update() {
var val = attr
.map(function(a) {
return $(a).val();
})
.join(",");
$("#attr3").val(val);
}
That being said I'd probably go with a simpler solution like this.
// set the keyup event handler and add all inputs to an array.
var inputs = $("#candy :input").keyup(function() {
update();
}).get();
// read all input values into comma separated string and update attr3
function update() {
var val = inputs.map(function(i) {
return $(i).val();
}).join(",");
$("#attr3").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attr3" name="username" value="">
Update: Support dynamically added inputs.
$(document).on("keyup", "#candy :input", function() {
update();
});
function update() {
var val = $("#candy :input").get().map(function(i) {
return $(i).val();
}).join(",");
$("#attrFinal").val(val);
}
var count = 3;
$("#add").click(function() {
$("#candy").append("<input type='text' id='attr" + count++ + "' name='emailAddress' />");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attrFinal" name="username" value="">
<button id="add">Add New</button>
I have 4 input tags.
<input type="number" class="br1" name="first">
<input type="number" class="br1" name="secound">
<input type="number" class="br1" name="third">
<input type="number" class="br1" name="fourth">
I want to set maxlength (4 numbers) for every input tag. I tried to set maxlength but it doesn't work. Also, when I enter 4 numbers in one input tag, I want to automaticlly input in next input tag.
Thanks.
If you want to use maxlength change type of input to text. Then you can parse all you your inputs strings to a number.
$(".br1").keyup(function () {
if (this.value.length == this.maxLength) {
var $next = $(this).next('.br1');
if ($next.length)
$(this).next('.br1').focus();
else
$(this).blur();
}
});
$(".btn").click(function() {
var string = "";
$(".br1").each(function() {
string += this.value;
});
number = parseInt(string);
console.log(number);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="br1" name="first" maxlength=4>
<input type="text" class="br1" name="secound" maxlength=4>
<input type="text" class="br1" name="third" maxlength=4>
<input type="text" class="br1" name="fourth" maxlength=4>
<button class="btn">toNumber</button>
Use max="9999" and min="0000" to set the maximum value for input type number.
As per http://w3c.github.io/html/sec-forms.html#the-maxlength-and-minlength-attributes maxlength is not valid for input of type number.
You can use input event attached to .br1 elements, .slice() with parameters 0, -1 to remove character if .length of .value is greater than 4
var inputs = document.querySelectorAll(".br1");
for (let input of inputs) {
input.oninput = () => {
if (input.value.length > 4) {
input.value = input.value.slice(0, -1)
}
}
}
<input type="number" class="br1" name="first">
<input type="number" class="br1" name="secound">
<input type="number" class="br1" name="third">
<input type="number" class="br1" name="fourth">
You can do this using only javascript. Also note the maxLength attribute don't work on number, so you may need to use input type='text'
Here is snippet
// get the input
var inputBox = document.getElementsByClassName("br1")
// loop through the array of input
for (var i = 0; i < inputBox.length; i++) {
// creating a closure
(function(x) {
// adding event listener to each of the input
inputBox[x].addEventListener('keydown', function(x) {
// checking value of maxLength
var maxLength = parseInt(this.attributes["maxlength"].value, 10);
// length of the input value
var myLength = this.value.length;
// if both are equal then find the next sibling
if (myLength >= maxLength) {
var next = this.nextElementSibling
// if the next sibling is input, set focus to it
if (next.tagName.toLowerCase() === "input") {
next.focus();
}
}
})
}(i))
}
It as simple as posible, Try this:
$("input[type=number]").keypress(function (e) {
var el = $(this);
var currentValue = el.val();
var char = String.fromCharCode(e.keyCode || e.which);
if (currentValue.length === 3) {
el.val(currentValue + char);
e.preventDefault();
el.next().focus();
} else if (currentValue.length >= 4) {
e.preventDefault();
}
})
input[type=number]{
width:60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" class="br1" name="first">
<input type="number" class="br2" name="first">
<input type="number" class="br3" name="first">
<input type="number" class="br4" name="first">
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>
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.