Javascript get value of current number input field - javascript

I am trying to make a shopping cart. Now i want to update the price of the item when the amount is changed, but when there are more than one items the onchange method only reacts on the first one. They have the same name. I can give them an other name but how will i then get the name of that input field.
I hope someone can help me with this.
Thanks in advance.
function updatePrice() {
var element = this;
console.log(element.value);
}

Your onchange event should iterate over all input fields.
If you give your fields a common identifier (a data-id attribute or a class name), then the process is quite trivial:
document.body.addEventListener("change", ()=> calc());
function calc(){
let items = document.querySelectorAll(".inp");
let total = 0.0;
for (let i = 0; i < items.length; i++) {
total += parseFloat(items[i].value);
}
document.querySelector(".result").value = total.toFixed(2);
}
calc();
<input type="text" class="inp" value="10.00">
<input type="text" class="inp" value="15.00">
<input type="text" class="inp" value="50.99">
<p>Result: <input type="text" class="result" value="00.00"></p>

Related

onchange not working with input field selected by class name

When I select the input field element by class name, the onchange event is not working. I want to change the value of the current changed input field. Codes are below:
// change current input field
function upperCase() {
// change current change input field
let x = document.getElementsByClassName('fname');
x.value = x.value.toUpperCase();
}
// call function when current element change
document.getElementsByClassName('fname').onChange = upperCase;
<input type="text" class="fname">
<input type="text" class="fname">
<input type="text" class="fname">
<input type="text" class="fname">
Please, I also want to change the value of the current change input field.
document.getElementsByClassName returns a collection of elements, but you're trying to access the value like a single element.
You need to access each individual element, like this:
let inputs = document.getElementsByClassName('fname');
inputs[0].value = inputs[0].value.toUpperCase();
or even better would be to loop through them:
let inputs = document.getElementsByClassName('fname');
for (let i of inputs) {
i.value = i.value.toUpperCase();
}
edit to add the event it should be the same idea:
function upperCase() {
// change current change input field
let inputs = document.getElementsByClassName('fname');
for (let i of inputs) {
i.value = i.value.toUpperCase();
}
}
let inputs = document.getElementsByClassName('fname');
for (let i of inputs) {
i.addEventListener('change', upperCase);
}
<input type="text" class="fname">
<input type="text" class="fname">
<input type="text" class="fname">
<input type="text" class="fname">
let x = document.getElementsByClassName('fname'); returns an array of objects, you need to work with the values of the array, for example:
let arrayFName = document.getElementsByClassName('fname');
for (let i of arrayFName) {
i.value = i.value.toUpperCase();
}
And the same happens with the onchange property:
for (let j of arrayFName) {
j.onChange = upperCase;
}
Hope it helps!
Replace your
document.getElementsByClassName('fname').onChange = upperCase;
with
const selectElement = document.querySelector('.fname');
selectElement.addEventListener('change', () => {
upperCase();
});
As others point out, when you have more then one element you should illiterate all and call function when it change. So basically something like this will do the work:
var x = document.getElementsByClassName('fname');
for (var i=0; i < x.length; i++) {
x[i].addEventListener('change', changeToUpperCase);
}
function changeToUpperCase(t) {
this.value= this.value.toUpperCase().replace(/ /g,'');
}
<input type="text" class="fname">
<input type="text" class="fname">
<input type="text" class="fname">
<input type="text" class="fname">

Compare input text with person name belongs to only one input number id

Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}

applying onkeyup function simultaneously on multiple textboxes

Suppose I have a column of 1+7 text box. Name of the first box is mm1 and the other boxes are respectively dd1, dd2, ...., dd7. I want to write a javascript function so that all the values in the textboxes dd1, dd2,...,dd7 are multiplied by N if I put N in the first textbox namely mm1. I can write the javascript function , but how to make its effect in all boxes simultaneously? I have tried the following code. But it can effect only one box depending on the value of $i. If we can create a loop for $i taking values 1 to 7, then perhaps the problem will be solved. Any clue please.
<?php $i=3?>
<input type="text" size="1" id="mm1" name="mm1"
maxlength="2" onfocus="this.select()"
onkeyup="gft('dd<?php echo $i?>', 'mm1')"
>
Try this, use class to logically group elements...
$('.mult').each(function(i,v){
var tt = parseFloat($(this).val());
$(this).attr('data-val',$(this).val());
});
$('.myVal').on('keyup',function(e){
var t = $(this).val();
if(!t) t = 0;
$('.mult').each(function(i,v){
if(t>0){
var tt = parseFloat($(this).attr('data-val')) * t;
$(this).val(tt);
}
});
});
Find working fiddle here
function gft(x){
n = 5;
c = x * n;
textInputs[0].value = c;
textInputs[1].value = c;
textInputs[2].value = c;
}
var textInputs = document.querySelectorAll('input[type=text]');
//this eventlistener is made to listen for key movement on all text fields that are of type text
for(i=0;i<textInputs.length;i++){
textInputs[i].addEventListener('keyup',function(){
//gft will execute an equation whenever one of these fields change
//also, it will change all the values inside the textfield simultaneously
gft(this.value);
},false);
}
I made a JSFiddle using only JavaScript (no jQuery):
HTML
<input type="number" onkeyup="multiply(this)"/>
<input type="number" value="1" class="multiply-this"/>
<input type="number" value="2" class="multiply-this"/>
<input type="number" value="3" class="multiply-this"/>
<input type="number" value="4" class="multiply-this"/>
<input type="number" value="5" class="multiply-this"/>
<input type="number" value="6" class="multiply-this"/>
<input type="number" value="7" class="multiply-this"/>
JavaScript
function multiply(first){
var value = +first.value;
var textboxes = document.getElementsByClassName("multiply-this");
for(var i = 0; i < textboxes.length; i++){
var textbox = textboxes[i];
if(textbox.attributes.initialValue){
textbox.value = textbox.attributes.initialValue.value;
} else {
textbox.setAttribute("initialValue", textbox.value);
}
textbox.value = +textbox.value * value;
}
}
window.onload = function(){
var textboxes = document.getElementsByClassName("multiply-this");
for(var i = 0; i < textboxes.length; i++){
var textbox = textboxes[i];
textbox.onkeyup = function(){
this.setAttribute("initialValue", this.value);
}
}
}
I added functionality to remember what value the textboxes had at first. But you can still change it if you specifically change one of the 7 textboxes that gets multiplied.
EDIT
You can also add this if you want it to multiply after changing one of the values:
textbox.onblur = function(){
multiply(document.getElementById("multiplyer"));
}
JSFiddle

Sum up all text boxes with a particular class name?

I have a grid, with one of the columns containing a textbox, where a user can type in a dollar amount. The text boxes are declared as:
<input class="change-handled" sub-category-id="83" data-id="" style="text-align: right; width: 100%" type="number" value="">
Some are all decorated with the class "change-handled".
What I need to do, is, using javascript/jquery, sum up all the boxes which are using that class, and display the total elsewhere on the screen.
How can I have a global event, that would allow this to occur when ever I exit one of the boxes (i.e: Tab out, or ENTER out).
At the moment, I have an event which doesn't do much at the moment, which will be used:
$('body').on('change', 'input.change-handled', SaveData);
function SaveData() {
var dataId = $(this).attr('data-id');
var categoryId = $(this).attr('sub-category-id');
var value = $(this).val();
}
How can I use that SaveData event, to find all the editboxes with the 'change-handled' class, sum up their values, and display it somewhere?
In plain JavaScript:
var changeHandled = [].slice.call(document.querySelectorAll('.change-handled'));
var total = document.querySelector('.total');
function calc() {
total.textContent = changeHandled.reduce(function(total, el) {
return total += Number(el.value);
}, 0);
}
changeHandled.forEach(function(el) {
el.onblur = calc;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
I think what you're looking for is the blur event.
$('body').on('blur', 'input.change-handled', UpdateTotal);
function UpdateTotal() {
var total = 0;
var $changeInputs = $('input.change-handled');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
Here's how you can sum up the values:
var total = 0;
$(".change-handled").each(function(index, box) {
total += parseInt($(box).val(), 10);
});
You would then display them by using the text or html functions provided by jQuery on elements.
This can be used from anywhere in your code, including the event handler.

Javascript calculation using input and span fields

<input type="number" name="quantity" id="quantity">
<span id="price">4000</span>
<input type="text" value="" id="total" readonly>
<input type="button" value="calculate Total Price" onClick="calculate()">
I need values from field name="quantity" and id="price" above and calculate using javascript function and to display it in field id="total" only when I click calculate button. I tried the javascript function below but the result is showing as NaN.
function calculate(tot) {
var quan = document.getElementsByName('quantity').value;
var pri = document.getElementById('price');
var pr = parseInt(pri);
var tot = quan * pr;
document.getElementById("total").value = tot;
}
Whenever you see a method in plural, such as getElementsByName it gets multiple elements, or what we call a nodeList, and even if there's only one matching element, you still get a nodeList, and a nodeList has no value, you can access a nodeList like an array and get the first element in the list like :
var quan = document.getElementsByName('quantity')[0].value;
Also, getElementById gets an element, not a number, you'd have to get the innerHTML
var pri = document.getElementById('price').innerHTML;
and remember the radix for parseInt
parseInt(pri, 10)
not that you really need to parse it when you're multiplying
FIDDLE
You will need a for loop and iterate over every individual value and put that in a value. Like this:
for(i=0; i<quan.length; i++) {
var total+= quan[i];
}

Categories

Resources