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.
Related
I tried to validate user input whether user input is a number or string by using isNaN or Type but it is not working. I wrote the if statement inside my function to validate user inputs. I want to user to prompt a number only, not a string. If user input is a string, I would like to pop up an alert to the user.
Can anyone can spot any mistake on my code? Either I put the code incorrectly or I missed something.
function updateTotal(){
var total = 0;
var list = document.getElementsByClassName('input');
var values = [];
for (var i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
total = values.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
if (isNaN(list)) {
alert("Error on input");
}
avgMarks = total / 5;
document.getElementById("total").value = total;
document.getElementById("display").value = avgMarks;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ordering form</title>
</head>
<body>
<h1>Get marks</h1>
<div>
<form id="form" method="post">
<label for="marks">Enter your 5 marks: </label><br>
<p>Mark 1</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 2</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 2</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 4</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 5</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Total 5 marks : </p>
<input type="text" name="totalMarks" id="total" value=""><br>
<p>The average of your marks is : </p>
<input type="text" name="avgMarks" id="display" value="">
<br>
</form>
</div>
<!--JavaScript-->
<script src="debug1_with_error.js"></script>
</body>
</html>
The variable list is a NodeList of elements, not what you want to test. The values you want to test are each individual value, one at a time, in your values array, or just isNaN(total), because NaN would come through in the total if any one value were NaN.
Can I have some inputs on this ?
Issue
When a form or a parent element of a form is modified, the text that was typed inside the inputs of the form get cleared. As this snipper show :
function modifyParent() {
document.getElementById("parent").innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
<input type="text" id="child">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>
Hello everyone,
Solution 1
I found a first esay way to prevent it if I know where the parent is modified. As this snipper show
function modifyParent() {
var child = document.getElementById("child");
child.setAttribute("value", child.value)
document.getElementById("parent").innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
<input type="text" id="child" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>
This solution look great, but only if i know where ans when the parent is modified. Also if i have a multiple inputs i need to loop on document.getElementsByTagName("input").
Solution 2
Since i dont know how many buttons i have and how many inputs, this is my best solution so far :
function modifyParent() {
setInputValues();
document.getElementById("parent").innerHTML += "<br>a line get added";
}
function setInputValues() {
for (var c of document.getElementsByTagName("input"))
c.setAttribute("value", c.value);
}
<div id="parent">
<form>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>
It work well for multiple inputs but i have to call the setInputValues() function before i modify any parent everytime. I started to consider to add setInterval on this function but I stop here because i'm starting to go a bit far and it's very likely that their is a better way.
Any help will be apreciated
A cleaner solution is to use a new element for the messages. This way you can set the messages inside a container without messing with the inputs.
const messageBox = document.querySelector(".messages");
function modifyParent() {
messageBox.innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
<div class="messages"></div>
</div>
Another quick notice, innerHTML is vulnerable for XSS attacks Try using createElement and appendChild if possible.
const parent = document.getElementById("parent");
function modifyParent() {
const br = document.createElement("br");
const text = document.createTextNode("a line get added");
parent.appendChild(br);
parent.appendChild(text);
}
<div id="parent">
<form>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
<div class="messages"></div>
</div>
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/
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 );
}
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);