multiply form values from form array with JS - javascript

I have html form with arrays:
<form method="post" id="formaa" name="form">
<div id="fields">
<div id="divas1" class="row">
<img src="d.jpg" /><a href="#" id="uid1" onClick="u(this);">
<img src="u.jpg" /></a><input type="text" name="ite[]" id="item" /><input type="text" name="q[]" id="quantity" class="quant" size="3" />
<input type="text" name="pr[]" id="price" size="10" class="kaina" onkeyup="update();"/><input type="text" name="sum[]" id="suma" size="10" disabled="disabled"/></div>
</div>
<br />
<input type="button" name="nw" id="new" value="ADD" onClick="naujas('laukeliai');" /><br />
Total: <input type="text" name="sumaa[]" id="suma" size="10" disabled="disabled"/>
</form>
Each time I push forms ADD button, inside the <div id="fields"> is included new div block <div id=divas(i++)> I need multiply qp[] and pr[] values and dynamicaly add to sum field, need do multiply price and quantity of each product seperately and get final each product price (not all products total).
first tried to get all values and filter these two, but couldnt figure out...
var form = document.getElementsByName('form')[0];
var inputs = form.getElementsByTagName('input');
for (var i = 0, j = inputs.length; i < j; i++) {
var element = inputs[i];
alert(element.value);
}
How to extract from this array only needed values and multiply? Thanks for advices.

Assuming you want to generate the sum of the prices for all the products and quantities you bought, you would first rewrite your HTML as:
<form id="example_form">
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price"></input>
</div>
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price"></input>
</div>
<!-- ... many more rows -->
<input type="text" disabled id="sum" name="sum"></input>
</form>
Use jQuery to make field access easier. Using JQuery, you would use the following JS:
function update() {
var total = 0;
$("#example_form div.row").each(function(i,o){
total += $(o).find(".quant").val() *
$(o).find(".price").val();
});
$("#example_form #sum").val(total);
}
This will update totals for you. To do this each time any number is changed, you would need to register it with the corresponding fields, using something like
$("#example_form div.row input").change(update);
Have I convinced you of using JQuery? See it working at http://jsfiddle.net/UnYJ3/2/

you can read form array in way as below
frmRefer = document.getElementByTagName("form")[0];
for(i= 0 ; i<frmRefer.elements["ite[]"].length;i++){
alert(frmRefer.elements["ite[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["quant[]"].length;i++){
alert(frmRefer.elements["quant[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["pr[]"].length;i++){
alert(frmRefer.elements["pr[]"][i].value );
}

Related

Sum answer not displaying

I have a program that I am currently trying to total.
The program is to have 10 numbers add into each text box and when the user hits the Sum button the program runs through the Add function and returns the total after the words 'Sum: '. The pages are linked with <script src="functions.js"></script> below the title tags.
Below are both pages.
function Add() {
var add_entries = 0;
for (i = 1; i <= 11; i++) {
var textentry = "Text" + i;
var x = Number(document.getElementById(textentry).value);
add_entries += x;
}
console.log(add_entries);
document.getElementById("Sum: ").innerHTML = add_entries;
}
Enter student test scores for all text boxes
<br>
<br>
<div>Blank responses will be treated as zeros.</div>
<br>
<br>
<div>Susan: <input id="Text1" type="text" /></div>
<div>Harry: <input id="Text2" type="text" /></div>
<div>Joe: <input id="Text3" type="text" /></div>
<div>Bill: <input id="Text4" type="text" /></div>
<div>Mary: <input id="Text5" type="text" /></div>
<div>Ken: <input id="Text6" type="text" /></div>
<div>Paul: <input id="Text7" type="text" /></div>
<div>John: <input id="Text8" type="text" /></div>
<div>Nora: <input id="Text9" type="text" /></div>
<div>Cindy: <input id="Text10" type="text" /></div>
<input id="Sum" type="button" value="Sum" onclick="Add()" />
<input id="Avg" type="button" value="Average" onclick="Avg()" />
<input id="High" type="button" value="Highest" onclick="Max()" />
<input id="Low" type="button" value="Lowest" onclick="Min()" />
<div>Sum: </div>
<div>Average: </div>
<div>Highest: </div>
<div>Lowest: </div>
document.getElementById("Sum: ").innerHTML = add_entries;
That's not a valid id. Give your div an id and use that.
<div id="mySum">Sum: </div>
document.getElementById("mySum").innerHTML = add_entries;
If you want to retain the "Sum:" you can use a span.
<div>Sum: <span id="mySum"></span></div>
document.getElementById("mySum").innerHTML = add_entries;
The for statement goes one step too far, if you check the console you will see an error stating something like, "TypeError: document.getElementById(...) is null", thats because its checking id="Text11"
change:
for (i = 1; i <= 11; i++)
to:
for (i = 1; i <= 10; i++)
and maybe even check that document.getElementById(textentry) doesn't return null before using it.
And of course, "use parseInt instead of Number" as Ameer said, or use a plus sign :/
+(document.getElementById(textentry).value);
for (i = 1; i <= 11; i++) 11 needs to be changed to 10 because you dont have Text11
document.getElementById("Sum: ").innerHTML = add_entries; ID is not correct
if you want the output set to your sum div you need to set an ID on it and put the id in document.getElementById(HERE)
EDIT Answer:
change this line
document.getElementById("Sum: ").innerHTML = add_entries;
to
document.getElementById("sumDiv").innerHTML = 'Sum: ' + add_entries;
and then add an ID to your div were you want the output to be
Like this <div id="sumDiv">Sum: </div>
In your for loop you're reaching 11, I can only see 10 text inputs in your HTML.

How to limit the input based on the value of another input using javascript

Html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2">
Paid Balance</strong>: <input type="text" name="paidbalance" id="paidbalance" class="form-control" />
</div>
<div class="col-md-2" >
Balance</strong>: <input type="text" name="balance" id="balance" class="form-control" value="200" readonly/>
</div>
Hello, Can anyone help me with this problem. How to limit the input based on the value of another input using javascript .
For Example the Value of Balance Input is 200 so that the possible input in PaidBalance is within 0-200 only.
Sorry, I'm just a student. Thanks :):)
Something like this?
$("#paidbalance").keyup(()=>{
const balance = parseFloat($("#balance").val())
const paidBalance = parseFloat($("#paidbalance").val())
if( paidBalance > balance)
$("#paidbalance").val(balance)
else if(paidBalance < 0)
$("#paidbalance").val(0)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Paid Balance
</strong>: <input type="text" name="paidbalance" id="paidbalance" class="form-control" />
Balance
</strong>: <input type="text" name="balance" id="balance" class="form-control" value="200" readonly/>
This is with pure javascript without jquery. Also, note that the accepted answer doesn't work if user paste some value with mouse right-click: paste option.
function f1()
{
var max = Number(document.getElementById("balance").value);
var paid = document.getElementById("paidbalance");
var v = Number(paid.value);
//if(isNaN(v)) {...} //input is not a number
if(v>max) {
paid.focus(); //to keep focus on input
paid.value=max; //you may comment out this line to don't override value
}
}
<div class="col-md-2">
Paid Balance</strong>: <input type="text" name="paidbalance" id="paidbalance" class="form-control" oninput="f1()" />
</div>
<div class="col-md-2" >
Balance</strong>: <input type="text" name="balance" id="balance" class="form-control" value="200" />
</div>
You might wanna change the type to number in this case and add max property in input. If the value of balance Input is different every time. You might considering assign it to a variable and pass it to the max property
Paid Balance</strong>:
<input type="number" name="paidbalance" id="paidbalance" max="200" class="form-control" />
Change the input to type="number" and add jQuery like this:
var balance = $('#balance')
var paidBalance = $('#paidbalance')
paidBalance[0].setAttribute('max', balance.val())
Example:
https://jsfiddle.net/Daniel_Knights/t4hb0z7p/8/

HTML form:input calculate 2 fields

I'm using spring mvc for my form which has the tag
<form:input type="number" class="value1" id="value1" path="commandName.object.field1" />
<form:input type="number" class="value1" id="value1" path="commandName.object.field2" />
<input type="text" disabled="disabled" id="result" />
I read some questions in regards to calculations and even found a js fiddle:
http://jsfiddle.net/g7zz6/1125/
how do i calculate 2 input fields and put results in 3rd input field
but it doesn't work when the input tag is form:input. Is it possible to do auto calculation of the 2 form:input fields upon keyin and update the 3rd input?
Here you go
HTML
<input type="text" class="input value1">
<input type="text" class="input value2 ">
<input type="text" disabled="disabled" id="result">
JS
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var val1 = parseInt($('.value1').val());
var val2 = parseInt($('.value2').val());
var sum = val1+val2;
$("input#result").val(sum);
});
});
Fiddle https://jsfiddle.net/1sbvfzcc/
$(document).ready(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
$('.input').blur(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input value1" value="20">
<input type="text" class="input value2" value="30">
<input type="text" disabled="disabled" id="result">
Please check the code this might help you understand why your code is not working.
You are using document ready function which is not able to get the value as no default value for input box.
I have added a new blur function which will calculate the value on change of input box
Try this your form tag syntax was wrong
$('form').on('keyup' ,'.value1', function(){
var k=0;
$('.value1').each(function(){
k +=parseFloat($(this).val()|0);
})
$('input:text').val(k)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field1" />
</form>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field2" />
</form>
<input type="text" disabled="disabled" id="result" />

jQuery add rows dynamically with unique input field ids

Trying to add dynamic rows (max up to 6): But it adds 2 rows at a time for some reason. So this is the order. By default 1 row is displayed, once AddPO is clicked, it inserts 2 rows, again 2 rows on button click and then ofcourse 1 since it checks for max 6 rows.
Why is it not inserting one row at a time?
Here is the code:
<script>
$(document).ready(function(){
$('#addPO').click(addPO)
});
var current = 1;
function addPO() {
current++;
if (current < 7){
var strToAdd = '<p><input id="FinalPONumber'+current+'" name="FinalPONumber'+current+'" size="20" /> <input id="FinalPOAmount'+current+'" name="FinalPOAmount'+current+'" size="20" /><input type="file" id="FinalPOFile'+current+'" name="FinalPOFile'+current+'"/></p>'
$('#mainField').append(strToAdd)
}
}
</script>
html:
<div id="mainField">
<p>
<input type="text" id="FinalPONumber1" name="FinalPONumber1" size="20" />
<input type="text" id="FinalPOAmount1" name="FinalPOAmount1" size="20" />
<input type="file" id="FinalPOFile1" name="FinalPOFile1"/>
</p>
</div>
<p>
<input type="button" id="addPO" value="Add Final PO">

Can not pass html array to JS

Hi I'm having trouble sending html form array to JS. I have dynamic html form and some fields:
<div id="fields">
<input type="text" name="ppav[]" id="p" />
<input type="text" name="quantity[]" id="q" size="3" />
<input type="text" name="price[]" id="pr" size="10" />
<input type="text" name="sum" id="su" size="10" disabled="disabled"/>
<br />
</div>
in JS i tried using this function but getting undefined alert instead of result:
var welements = document.getElementsByName('ppav[]');
for (var i = 0, j = welements.length; i < j; i++) {
var an_element = welements[i];
alert(an_element.selectedIndex);
}
What did you expect? the selectedIndex property returns the index of the selected option in a select element. If you want the value of your input fields, try alert(an_element.value);

Categories

Resources