Multiply input values - javascript

Inputs are invisible to jQuery when they are appended.
THere are 3 inputs
<input class="bul-order-info__input bul-order-info__price" type="text" name="price" value="500" readonly>
<input class="bul-order-info__input bul-order-info__qnt" type="number" name="quantity" min="1" value="1">
<input class="bul-order-info__input bul-order-info__total" type="text" name="totalPrice" value="" readonly>
with this code
let $output = $("#output-value");
let $price = $(".bul-order-info__price");
$(document).on('change', ".bul-order-info__qnt", function () {
let value = parseFloat($(this).val());
$output.val(value * $price.val());
});
If I have these inputs in my html created manually, I can multiply the inputs value and add the result into the total price input.
But I need these inputs to appear after the click event, so I append them. After that they become invisible to jQuery, hence nothing works.
How can I make these inputs appear on the page, in the form, and then manipulate their values?

You did only one mistake while assigning the value to the input field which displays the multiplication result
let $output = $("#output-value");
let $price = $(".bul-order-info__price");
$(document).on('change', ".bul-order-info__qnt", function () {
let value = parseFloat($(this).val());
let tot=value * $price.val();
$(".bul-order-info__total").val(tot);
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input class="bul-order-info__input bul-order-info__price" type="text" name="price" value="500" readonly>
<input class="bul-order-info__input bul-order-info__qnt" type="number" name="quantity" min="1" value="1">
<input class="bul-order-info__input bul-order-info__total" type="text" name="totalPrice" value="" readonly>
</body>
</html>

Jquery can't find dynamically generated elements directly.
You can access them using it's parent which is not appended dynamically.
$(document).on('change', "body .bul-order-info__qnt", function () {
let value = parseFloat($(this).val());
$output.val(value * $price.val());
});

Related

How to store an Input value and have it appear inside a <p> element on another page

I'm very new to Javascript/JQuery and wanted to know how i can store the values of these Inputs:
<input type="number" id="rooms_amount_bedroom" autocomplete="off" value="0">
<input type="number" id="rooms_amount_bathrooms"autocomplete="off" value="0">
<input type="number" id="rooms_amount_kitchens" autocomplete="off" value="0">
inside this input <p> element:
<p class="chosen_service__room_types">""</p>
using pure Javascript. Thanks for the help!
You can add an Event Listener to the input and set its value in localStorage.
In case you want to update the storage every time the user inputs you can do this:
document.getElementById('rooms_amount_bedroom').addEventListener('input', function(){
let val = this.value;
localStorage.setItem('input',val)
})
<input type="number" id="rooms_amount_bedroom" autocomplete="off" value="0">
In case you want to update the storage once on a button click:
document.getElementById('btn').addEventListener('click', function(){
let val = document.getElementById('rooms_amount_bedroom').value;
localStorage.setItem('input',val)
})
<input type="number" id="rooms_amount_bedroom" autocomplete="off" value="0">
<button id="btn">Update</button>
Then, on the other page, you can set the stored value to the paragraph's content on load as follows:
window.onload = function(){
document.getElementsByClassName('chosen_service__room_types')[0].innerHTML = localStorage.getItem('input');
}
<p class="chosen_service__room_types"></p>
Example 1. Using a link
page 1
Change WhateverItIsYouArClicking to #link if what you are clicking has id="link"
or ".someClass" if what you are clicking has class="someClass"
window.addEventListener("load",function() {
document.querySelector("WhateverItIsYouArClicking").addEventListener("click",function(e) {
e.preventDefault(); // if it is a link or a submit button
const fields = [...document.querySelectorAll("input[type=number]")].map(fld => fld.id+"="+fld.value);
location = "index.html?"+fields.join("&");
})
})
Page 2
window.addEventListener("load",function() {
const url = new URL(location.href);
document.querySelector(".rooms_amount_bedroom").textContent = url.searchParams.get("rooms_amount_bedroom");
document.querySelector(".rooms_amount_bathrooms").textContent = url.searchParams.get("rooms_amount_bathrooms");
document.querySelector(".rooms_amount_kitchens").textContent = url.searchParams.get("rooms_amount_kitchens");
})
Example 2 using a form
<form action="index.html">
<input type="number" id="rooms_amount_bedroom" autocomplete="off" value="0">
<input type="number" id="rooms_amount_bathrooms"autocomplete="off" value="0">
<input type="number" id="rooms_amount_kitchens" autocomplete="off" value="0">
<input type="submit" />
</form>
and on page 2 have the same as above

Why does my javascript not output the total of four numbers in an html form?

This is a small part of a larger project. Why does it not output the total of the four number and display in the fifth text box?
<body>
<form action="acknolcupcard" method="post" name="CupCard" id="CupCard" target="_self">
<p></p>
<input name="OneH1" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
<input name="OneH2" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
<input name="OneH3" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
<input name="OneH4" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
<label for="S1TotH"></label>
<input type="text" name="S1TotH" id="S1TotH" value="0" size= "10" maxlength= "10"/>
</form>
<script type="text/javascript">
function calc(){
var S1TotH =<br />
document.getElementById('OneH1').value +
document.getElementById('OneH2').value +
document.getElementById('OneH3').value +
document.getElementById('OneH4').value;
document.getElementById('S1TotH').value = S1TotH;
}
</script>
</body>
You need to add id as an attribute:
<input id="OneH1" name="OneH1" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
Also in order to call the method you should create a handler:
<script type="text/javascript">
function calc() {
// This doesn't work since <br/> has no type (e.g. var S1TotH = '<br />')
var S1TotH =<br />
/* This values need to be stored in a variable or used in some way
(e.g. var S1TotH = document.getElementById('OneH1').value + document...). But be careful because in this way you are concatenating the
values, not adding them. If you want to add them you
should convert them to numbers (e.g. parseFloat(document.getElementById('OneH1').value)) */
document.getElementById('OneH1').value +
document.getElementById('OneH2').value +
document.getElementById('OneH3').value +
document.getElementById('OneH4').value;
document.getElementById('S1TotH').value = S1TotH;
}
// use 'input' or 'change' event
document.querySelector('input').addEventListener('input', function () {
calc();
});
</script>
You don't call the function
Mentioning the name of a variable (even if the value of that variable is a function) doesn't call the function.
You need to put (argument, list) after it.
onchange="calc()"
Intrinsic event attributes have a bunch of problems though (e.g this one) and are best avoided.
You could use a delegated event listener instead.
function calc(event) {
const input = event.target;
console.log(input.value);
}
document.querySelector("form").addEventListener("change", calc);
<form>
<input type="number">
<input type="number">
<input type="number">
<input type="number">
</form>
You have no ids
Then it will run, but error, because you are using getElementById without having elements with id attributes.
You are concatenating not adding
Once you fix that, you will still not be adding up the values because + servers double duty as the concatenation operator and values are strings.
You need to convert them to numbers (e.g. with parseFloat).
This code should work, use oninput instead of onchange for live changes reflect, I resolved few other errors too.
<body>
<form action="acknolcupcard" method="post" name="CupCard" id="CupCard" target="_self">
<p></p>
<input name="OneH1" id="OneH1" type="number" value="0" size="5" maxlength="5" oninput="calc()"/>
<input name="OneH2" id="OneH2" type="number" value="0" size="5" maxlength="5" oninput="calc()"/>
<input name="OneH3" id="OneH3" type="number" value="0" size="5" maxlength="5" oninput="calc()"/>
<input name="OneH4" id="OneH4" type="number" value="0" size="5" maxlength="5" oninput="calc()"/>
<label for="S1TotH"></label>
<input type="text" name="S1TotH" id="S1TotH" value="0" size= "10" maxlength= "10"/>
</form>
<script type="text/javascript">
function calc(){
var S1TotH =
document.getElementById('OneH1').value +
document.getElementById('OneH2').value +
document.getElementById('OneH3').value +
document.getElementById('OneH4').value;
document.getElementById('S1TotH').value = S1TotH;
}
</script>
</body>
Above code will concate the values as these are strings values so far so you need to use the parseInt() function if you want to convert it into numbers

Iterate through N number of input boxes, updating each to their max value

Is there a way to give a bunch of inputs the same ID, and then iterate over them, when a checkbox is checked, and update their respective values to the MAX attribute? For example, with the following HTML:
CHECK ALL: <input type="checkbox" id="someIDname">
<input type="number" max="80" id="anotherIDname">
<input type="number" max="90" id="anotherIDname">
<input type="number" max="99" id="anotherIDname">
<input type="number" max="65" id="unrelated">
<input type="number" max="75" id="unrelated">
... and the JS is like this:
<script type="text/javascript">
$(document).ready(function() {
$('#someIDname').click(function(event) {
if(this.checked) {
$('#anotherIDname').each( function() {
var maxValue = $("#anotherIDname").attr("max");
document.getElementById("anotherIDname").value = maxValue;
});
}
});
});
</script>
I'd like to, when the checkbox is checked, have it fill in all of the MAX attributes from anything with the "anotherIDname" ID. (I'd then have three boxes, onewith 80, one with 90, one with 99. The other two are different IDs, so it would leave those alone.)
Total beginner with JS / jQuery here... The above script works on the 1st box, but does not update the others with the "anotherIDname" ID. (I thought maybe that ".each" would make it do them all, one at a time, but ... I guess that's not how it works. (I'm more of a PHP guy, normally, and that would be how something like this could maybe work if it was server-side.) Any thoughts appreciated.
There are few things wrong
id is always unique in the page.Same class is assigned to elements having same features
You should use $(this).val() to set the value
$(document).ready(function() {
$('#someIDname').click(function(event) {
if(this.checked) {
$('.anotherIDname').each( function() {
var maxValue = $(this).attr("max");
console.log(maxValue);
$(this).val(maxValue)
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="someIDname">
<input type="number" max="80" class="anotherIDname">
<input type="number" max="90" class="anotherIDname">
<input type="number" max="99" class="anotherIDname">
<input type="number" max="65" class="unrelated">
<input type="number" max="75" class="unrelated">
Added a class name and used querySelectorAll. Does this work as you want?
$(document).ready(function() {
$('#someIDname').click(function(event) {
if(this.checked) {
document.querySelectorAll('.max').forEach(a => {
a.value = a.max;
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CHECK ALL: <input type="checkbox" id="someIDname">
<input type="number" max="80" id="anotherIDname" class="max">
<input type="number" max="90" id="anotherIDname" class="max">
<input type="number" max="99" id="anotherIDname" class="max">
<input type="number" max="65" id="unrelated" class="max">
<input type="number" max="75" id="unrelated" class="max">
The id must be unique in the page. So, you can't use same id in several places. However, you can use same class in several places.
So, you'll need to change the id to class for eg.:
<input type="number" max="80" class="maxinput" />
And to set the value from max attribute:
$('.maxinput').val(function() {
return $(this).attr('max')
});
However, I would suggest to use data-* instead of simple attribute:
<input type="number" data-max="80" class="maxinput" />
And get the data value:
$('.maxinput').val(function() {
return $(this).data('max')
});
But I am still in surprise why you aren't simply setting their values initially?
<input type="number" class="maxinput" value="80" />

Calculate Arrays with input field instead of span or div

I'm trying to do a simple calculation onblur with arrays but it's not firing. If I change it to a span or div it works fine. Why isn't it working with an input field?
I need it to be an input field because it's easier to store the values in a database.
<input type="text" class="input-small" name="partnumber[]">
<input type="text" class="input-small" name="partdescription[]" >
<input type="text" class="input-small" name="partprice[]" onblur="doCalc(); calculate(); ">
<input type="text" class="input-small" name="partquantity[]" onblur="doCalc(); calculate(); ">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >
Calculation
function doCalc() {
var total = 0;
$('tr').each(function() {
$(this).find('.parttotal').html($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
});
$('.parttotal').each(function() {
total += parseInt($(this).text(),10);
});
}
Firstly, I wouldn't use inline events.. Here I've used delegated events, an advantage here if you dynamically add any more lines, it will still work..
Next make sure each line has some sort of wrapper for each line, here I've used a simple DIV. Yousr might be your TR..
The rest then becomes easy, as can be seen here, this example I've just included the price, qty & total, and done 2 lines for testing..
function calc() {
var h = $(this).closest('div');
var qty = h.find('[name="partquantity[]"]');
var price = h.find('[name="partprice[]"]');
var total = h.find('[name="parttotal[]"]');
total.val(qty.val() * price.val());
}
$('body').on('blur', '[name="partprice[]"],[name="partquantity[]"]', calc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" class="input-small" name="partprice[]">
<input type="text" class="input-small" name="partquantity[]">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >
</div>
<div>
<input type="text" class="input-small" name="partprice[]">
<input type="text" class="input-small" name="partquantity[]">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >
</div>
you can't use .html() to set the value of a textbox.
Change this line:
$(this).find('.parttotal').html($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
to
$(this).find('.parttotal').val($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
Note the change ('.parttotal').html becomes ('.parttotal').val

Array textboxes with onchange event

<INPUT name="Qty[]" id="Qty[]" type="text" class="south" />
<INPUT name="Amount[]" id="Amount[]" type="text" class="south"/>
<INPUT name="TotalAmount[]" id="TotalAmount[]" type="text" class="south" disabled="disabled"/>
Here i have problem with my code that i need to calculate multiply the first two textboxes. and that result will be appear into the last one, i mean third textbox as TotalAmount. Could you help me? here three textboxes appeared in single row with add button. when i submit the add button new created with three boxes again. I need to finish it in jquery of java script. please help me guys
First of all, remove the array-declaration, you're not using the the input fields as arrays. they are single values.
<INPUT name="Qty" id="Qty" type="text" class="south" />
<INPUT name="Amount" id="Amount" type="text" class="south"/>
<INPUT name="TotalAmount" id="TotalAmount" type="text" class="south" disabled="disabled"/>
And the jquery.
$(document).ready(function(){
qty = $("#Qty").val();
amount = $("Amount").val();
$("#Qty, #Amount").keyup(function(){
$("#TotalAmount").val((qty)*(amount));
});
});
Here is your JavaScript:
$(document).ready(function () {
var $quantity = $('#Qty\\[\\]'),
$amount = $('#Amount\\[\\]'),
$total = $('#TotalAmount\\[\\]'),
quantity,
amount;
$($quantity.add($amount)).keyup(function () {
quantity = Number($quantity.val().replace(/[^0-9,.]/g, ''));
amount = Number($amount.val().replace(/[^0-9,.]/g, ''));
$total.val(quantity * amount);
});
});
UPDATE Changed to keep the DOM ids the same in case they have to be that way. For an unmentioned reason as mentioned by #Ken Keenan.

Categories