Multiplication in jQuery dynamically - javascript

I am trying to make a multiplication function in jquery where which helps change the default value-based output.
For example - if I type the input#mainInput value then it will change all the inputs value base own his default value * input#mainInput and if the value == 'NaN' it will do dirent funcion.
Please help me how to I make this function in jQuery.
$(document).on('keyup', 'input#mainInput', function() {
thisParentQtyValueBox = $(this).val();
daughtersBoxValueAttr = $("input.input__bom").attr("inputid");
daughtersBoxValue = $("input#daughterInput_" + daughtersBoxValueAttr).val();
$("input#daughterInput_" + daughtersBoxValueAttr).val(thisParentQtyValueBox * daughtersBoxValue);
if ($("input#daughterInput_" + daughtersBoxValueAttr) == 'Nan') {
$("input#daughterInput_" + daughtersBoxValueAttr).val('3' * daughtersBoxValue)
}
});
//If
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" value="25" /><br/>

If I understand correctly, when the input is not a number, you want to do as if the input was 3.
Some issues in your code:
$("input.input__bom").attr("inputid") is always going to evaluate to 1, as only the first matching element is used. And it is strange to use this attribute value to then retrieve that element again via its id property.
You would need a loop somewhere so to visit each of the "input__bom" elements.
== 'Nan is never going to be true. You should in fact test the main input itself to see if it represents a valid number. For that you can use isNaN.
It is a bad idea to give these elements a unique id attribute. You can use jQuery to visit them each and deal with them. There is no need for such id attribute.
Don't use the keyup event for this, as input can be given in other ways than pressing keys (e.g. dragging text with mouse, or using the context menu to paste). Use the input event instead.
There is no good reason to use event delegation here on $(document). Just bind your listener directly the main input element.
Declare your variables with var (or let, const). It is bad practice to no do that (it makes your variables global).
It seems like the 5 "bom" input elements are not really intended for input, but for output. In that case the placeholder attribute makes no sense, and they should better be marked with the readonly attribute.
$("#mainInput").on('input', function() {
var mainInput = $(this).val();
var multiplier = +mainInput; // convert to number with unary +
// default value in case input is not a valid number, or is empty
if (Number.isNaN(multiplier) || !mainInput) {
multiplier = 3;
}
$('.input__bom').each(function() {
$(this).val( multiplier * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" type="text" readonly data-value="5" value="5"><br/>
<input class="input__bom" type="text" readonly data-value="10" value="10"><br/>
<input class="input__bom" type="text" readonly data-value="15" value="15"><br/>
<input class="input__bom" type="text" readonly data-value="20" value="20"><br/>
<input class="input__bom" type="text" readonly data-value="25" value="25" /><br/>

You have to store the default value in the data attr so then it will not multiple by result value and it will multiple by your default value. for dynamic multiplication, you can use jquery each. check below code.
$(document).on('input', 'input#mainInput', function() {
thisParentQtyValueBox = parseInt( $(this).val() );
if( Number.isNaN( thisParentQtyValueBox ) ){
thisParentQtyValueBox = 3;
}
$('.input__bom').each(function(){
$(this).val( thisParentQtyValueBox * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" data-value ="5" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" data-value ="10" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" data-value ="15" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" data-value ="20" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" data-value ="25" value="25" /><br/>

Related

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" />

how do i clone a multiple html input field with jquery

i have a complex div with input field somewhat like this
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<div id="section_toClone">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
</div>
<button id="add_more"> Add </button>
now when someone click on add i want something like this to happen
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="checkbox name tree[tree2][color] value="green">Green </input>
<input type="checkbox name tree[tree2][color] value="yellow">yellow </input>
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
<input type="checkbox name tree[tree3][color] value="green">Green </input>
<input type="checkbox name tree[tree3][color] value="yellow">yellow </input>
and so on..... but my script only clone doesnt change the value of tree from tree1 to tree2 to tree3 and so on.... here is my jquery script
$('#add_more').click(function(){
$("#section_toClone").clone(true).insertBefore("#add_more").find('input').val("").val('');
});
how do i increment that automatically?? i want to mention one more thing in actual html code. it has more then 3 input and 3 checkbox field
Don't even bother putting the numbers into the array keys. Just let PHP take care of it itself:
<input name="tree[fruit][]" value="foo" />
<input name="tree[fruit][]" value="bar" />
<input name="tree[fruit][]" value="baz" />
Any [] set which DOESN'T have an explicitly specified key will have one generated/assigned by PHP, and you'll end up with
$_POST['tree'] = array(
0 => 'foo',
1 => 'bar',
2 => 'baz'
);
As long as your form is generated consistently, browsers will submit the fields in the same order they appear in the HTML, so something like this will work:
<p>#1</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][]" value="large" />
<p>#2</p>
<input name="foo[color][]" value="puce" />
<input namke="foo[size][]" value="minuscule" />
and produce:
$_POST['color'] = array('red', 'puce');
| |
$_POST['size'] = array('large', 'minuscule');
But if you start mixing the order of the fields:
<p>#3</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][] value="large" />
<p>#4</p>
<input namke="foo[size][] value="minuscule" />
<input name="foo[color][] value="puce" />
$_POST['color'] = array('red', 'puce');
/
/
$_POST['size'] = array('minuscule', 'large');
Note how they're reversed.
I wouldn't post this without feeling a bit ashamed of how bad it is written, but the following solution does the trick. Badly.
var treeCount = 1;
$('#add_more').click(function(){
$("#section_toClone")
.clone(true)
.insertBefore("#add_more")
.find('input')
.val('')
.each(function(key,element){
var $element = $(element),
oldName = $element.attr('name'),
newName;
if(oldName){
newName = oldName.replace(/tree[0-9]+/, 'tree'+(treeCount+1));
$element.attr('name', newName);
}
else {
treeCount--;
}
})
.promise().done(function(){
treeCount++;
});
});
(please don't shoot me)

Give two text boxes the same value one is filled in using Javascript or jQuery

I have 2 textboxes with a type="number".
1 textbox is my 'master' textbox, then I have another subsequent textbox that I would like that IF the 'master' textbox is filled in with a number, the subsequent textbox would get the same value.
I thought about using the data- attribute but I am not sure how to target if the 'master' textbox is filled then, then subsequently put the same value in the sub textbox(es) with the same data- attribute.
In my example below I also use spans to create plus and minus buttons that adjust the value based on the value. This is in the JS section.
My current HTML is as follow:
<div id="masterTextboxes">
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<span class="addBtn AddMinusButton">+</span>
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Child" />
<span class="addBtn AddMinusButton">+</span>
</div>
<!--Values from Master Textboxes should populate into these textboxes as well.-->
<div id="subTextboxes">
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<span class="addBtn AddMinusButton">+</span>
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Child" />
<span class="addBtn AddMinusButton">+</span>
</div>
Javascript
<script>
$(document).ready(function () {
/*Add an minus buttons for variants*/
$(".AddMinusButton").on('click touchstart', function (event) {
event.preventDefault();
//Add button active style for touch.
var $button = $(this);
var oldValue = $button.parent().find("input").val();
var newVal = oldValue;
//Hide .decButton for oldValue
if (newVal == 0 || oldValue == 0 ) {
oldValue = 0;
}
else { $button.parent().find(".minusBtn").show(); }
if ($button.text() == "+") {
newVal = parseFloat(oldValue) + 1;
// Don't allow decrementing below zero
if (oldValue >= 1) {
newVal = parseFloat(oldValue) - 1;
}
}
$button.parent().find("input.attendeeQuantityInput").val(newVal);
//Sub textboxes should take value of master textboxes. Is this correct syntax?
//This is probably wrong.
$('#subTextboxes input').data("attendee").val(newVal);
});//End button click
});
</script>
I hope this makes sense on what I am trying to get out of this.
Thanks in advance.
I would like that IF the 'master' textbox is filled in with a number,
the subsequent textbox would get the same value.
You can do it like this:
<p>
<label>Master 1: <input type="number" id="master1" placeholder="0" /></label><br>
<label>Dependant 1: <input type="number" class="dependant1" placeholder="0" /></label>
</p>
<p>
<label>Master 2: <input type="number" id="master2" placeholder="0" /></label><br>
<label>Dependant 2: <input type="number" class="dependant2" placeholder="0" /></label><br>
<label>Dependant 2: <input type="number" class="dependant2" placeholder="0" /></label>
</p>
And in the JS:
$("input[id^='master']").on("change", function(){
var no = this.id.replace("master", "");
var selector = ".dependant" + no
$(selector).val(this.value);
});
This makes use of jQuery's attribute starts with selector and will work for any number of inputs provided the class names match.
Demo
You could do this:
HTML:
<div id="masterTextboxes">
<p>Master</p>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<input type="number" value="" placeholder="0" data-attendees="Child" />
</div>
<div id="subTextboxes">
<p>Sub</p>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<input type="number" value="" placeholder="0" data-attendees="Child" />
</div>
JS:
// On change in master inputs...
$("#masterTextboxes input", this).on("change", function() {
// Store Master inputs in master variable and Sub inputs in sub variable.
var master = $("#masterTextboxes input"),
sub = $("#subTextboxes input");
// Match master and sub values by using the master array key as reference.
$(sub[$.inArray($(this)[0], master)]).val( $(this).val() );
});
The jQuery code relies on the condition that the Sub inputs follow the same order as the Master's inside each respective div.
JSFiddle:
Here's a working JSFiddle for reference.

Simple reusable javascript averaging function for multiple forms on same page

I literally started trying to teach myself javascript less than 48 hours ago. Outside of just wanting to learn it I also have a small personal project I'm working on and using as sort of my working learn as I go example. But I've hit a problem, which I'm sure is rather basic, I'm just hampered by lack of much javascript knowledge.
Basically it is just an averaging problem.
There are going to be 4 inputs fields with the 4th being a rounded to the nearest whole number average of the first three fields.
This 4 field configuration is going to get used multiple times on the page.
I want it to work in "real time" and not with a calculate button so I'm assuming "onKeyup" is needed. (no validation of any kind is needed or submit or saving or anything)
The only code I've been able to get close is really really ugly, long, and convoluted. I can't help but think there is a very simple way to do it and just get the same function to apply to each grouping of inputs. It will look like below but probably much longer.
some text
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
some text
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
Thanks in advance. This is part of a larger problem but I've tried to strip it down to it's essence and seeing it work and understanding it will go a long way to helping me solve some other problems.
To start with use a different markup, there should only be a single id per page, so use classes, it make it easier to target everything too. Also if the effect is to use the last input as a display you can use readonly instead of disabled
<p>some text</p>
<div class="group">
<input class="a" type="number" /><br/>
<input class="b" type="number" /><br/>
<input class="c" type="number" /><br/>
<input class="final" value="0" readonly />
</div>
<p>some text</p>
<div class="group">
<input class="a" type="number" /><br/>
<input class="b" type="number" /><br/>
<input class="c" type="number" /><br/>
<input class="final" value="0" readonly />
</div>​
Here is an example done in jquery
$(function() {
$('.group input').on('click', function() {
var count = parseInt($(this).val()) || 0;
$(this).siblings(':not(.final)').each(function() {
if ($(this).val()) count = count + parseInt($(this).val());
});
$(this).siblings('.final').eq(0).val(count);
});
});
And the demo is here: http://jsfiddle.net/4S4Vp/1/
​
This should be understandable for your level. The second set of inputs will be named a-2 with calc(2) and so on.
<input id="a-1" type="number" onkeyup="calc(1)" value="0" /><br/>
<input id="b-1" type="number" onkeyup="calc(1)" value="0" /><br/>
<input id="c-1" type="number" onkeyup="calc(1)" value="0" /><br/>
<input id="final-1" value="0" disabled />
function calc( n ) {
var a = document.getElementById("a-" + n ).value;
var b = document.getElementById("b-" + n ).value;
var c = document.getElementById("c-" + n ).value;
document.getElementById("final-" + n ).value = Math.round((parseInt(a)+parseInt(b)+parseInt(c))/3);
}
This is really quick and dirty, but if you know how many inputs you have, this should work:
// these would instead be your textboxes
​var a = document.getElementById('a').value();
var b = document.getElementById('b').value();
var c = document.getElementById('c').value();
var avg = (a+b+b)/3;
document.getElementById('c').value() = avg;
Here is a jsfiddle so you can play with the idea and see if it works as you want it to.
Use jquery.
see the live demo on jsfiddle
some text
<div id="div1">
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
</div>
some text
<div id="div2">
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
</div>​
<script type="text/javascript">
$("#div1 input").bind('change keyup click',function(){
var final = 0;
$("#div1 input").not("#div1 #final").each(function(idx,el){
final += (el.value) ? parseInt(el.value) : 0;
});
$("#div1 #final").val(final/3);
});
$("#div2 input").bind('change keyup click',function(){
var final = 0;
$("#div2 input").not("#div2 #final").each(function(idx,el){
final += (el.value) ? parseInt(el.value) : 0;
});
$("#div2 #final").val(final/3);
});
​</script>
I hoped to flag this as duplicate, but because this answer does not have code, enjoy:
// find all inputs in the page and gather data trying to convert it to number
var data = [].map.call( document.querySelectorAll('input'), function (v) {
if (typeof v.value * 1 === 'NaN') {
return 'NaN';
}
return v.value * 1;
});
// not all data will be valid, so we filter it
data = data.filter( function (v) {
return !isNaN(v);
});
// and then calculate average
var avg = data.reduce( function (v, v1) {
return v + v1;
}) / data.length;

Categories