how to auto sum multiple inputbox inner loop in javascript - javascript

I want to calculate my input box inner looping and this bellow is what if done please help me to solve this issue
<?php
$jumlah_form = 3;
for($i=1; $i<=$jumlah_form; $i++){
?>
<input type="text" id="txt1" onkeyup="sum1();" /></br>
<?php
}
?>
<input type="text" id="txt2" value= "0" /></br>
<script>
function sum1() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtFirstNumberValue) ;
if (!isNaN(result)) {
document.getElementById('txt2').value = result;
}
}
</script>
Three input boxes are created by looping, I want to calculate three input box, and parse the result into result box whenever user input number

I think you are asking how to write the JavaScript so that it will add up the total of all the input boxes, no matter how many are created by the PHP?
If so then a good way would be to give all the textboxes the same class. Then, the JavaScript can just select all boxes with that class, loop through them and get the total value.
Here's a worked example using 3 textboxes (as if the PHP had generated them this way):
var textboxes = document.querySelectorAll(".sum");
textboxes.forEach(function(box) {
box.addEventListener("keyup", sumAll);
});
function sumAll() {
var total = 0;
textboxes.forEach(function(box) {
var val;
if (box.value == "") val = 0;
else val = parseInt(box.value);
total += val;
});
document.getElementById("total").innerText = total;
}
<input type="number" id="txt1" class="sum" value="0" /><br/>
<input type="number" id="txt2" class="sum" value="0" /><br/>
<input type="number" id="txt3" class="sum" value="0" /><br/>
<br/><br/> Total: <span id="total"></span>

To generate html with php:
$count = 5;
for($i=1;$i <= $count;$i++) {
echo "<input type='number' id='"."txt".i."' /></br>"
}
To calculate sum from inputs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<form onsubmit="submitForm(this); return false;" >
<input type="number" id='text1'>
<input type="number" id='text2'>
<input type="number" id='text3'>
<input type="number" id='text4'>
<input type="number" id='text5'>
<button type="submit" >Calculate</button>
</form>
<div>
<p>Result:</p>
<p id='result'></p>
</div>
<script>
function submitForm(form) {
let toReturn = 0;
const inputs = form.getElementsByTagName("input");
for(let x = 0; x < inputs.length; x++ ) {
toReturn += parseInt(inputs[x].value ? inputs[x].value : 0);
}
document.getElementById('result').innerHTML = toReturn;
return false;
}
</script>
</body>
</html>

Related

HTML, how to get always +1 sum

I'm doing a point counter in general and I have no idea how to do it anymore, so I would like to add +1 to the sum on the "=" button and add it only once if someone could help me, I would be grateful
Code: https://pastebin.com/C26VFyev
var result = 0;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + 1);
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>
Use a variable for what you add to the sum. Initialize it to 1 for the first time, than change it to 0 for future uses.
var result = 0;
var addition = 1;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + addition);
if (addition == 1) {
addition = 0;
}
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>

Sum two textbox values and get grade letter in third textbox

I have an HTML form with three textboxes. I want to sum them automatically using jQuery. At the same time, I want to use if–else statements to check if the result in third textbox is greater than 100. The value in the next (forth textbox)should be A.
See the code below :
<form>
<input type="text" class="number">
<input type="text" class="number">
<br>
<input type="text" id="total" disabled />
<input type="text" id="total2" disable />
<!--i want the letter A to appear in forth textbox if the value in third textbox is > 100 ---->
</form>
<script>
$('.number').keyup(function() {
var sum = 0;
$('.number').each(function() {
sum += Number($(this).val());
});
$('#total').val(sum);
if ($('#total').val(sum) > 100) {
form.total2.value = "A";
}
});
}
});
</script>
</body>
</html>
$('.number').on('keyup',function(){
var sum = 0;
var grade = 'B';
$('.number').each(function(){
sum += parseInt($(this).val());
});
$('#sum').text(sum);
if(sum>100){
grade = 'A';
}
$('#grade').text(grade);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="textbox" class="number" placeholder="number 1">
<input type="textbox" class="number" placeholder="number 2">
<div>
Your total mark is <span id="sum">0</span>.
<br>
Your grade is <span id="grade">F</span>.
</div>
You can use the following solution:
$('.number').keyup(function() {
var sum = 0;
$('.number').each(function() {
sum += parseInt($(this).val());
});
$('#total').val(sum);
if (sum > 100) {
$('#total2').val("A");}
});

JavaScript Fibonacci Calculator: How to output answer into text box?

I am currently trying to make a calculator that takes a numerical input (n) and shows the Fibonacci number to the nth sequence. I am a beginner at Javascript and just can't seem to make my code work:
HTML:
<head>
<script src="calculator.js"></script>
</head>
<body>
<input type="number" name="Input" value="" id="userInput" / >
<input type="button" value="Go" onclick="calculate();" />
<input type="number" name="Answer" id="userAnswer" />
</body>
JavaScript:
var input = document.getElementById("userInput");
var output = document.getElementById("userAnswer");
var answer;
function calculate(){
n = input.value;
if (n < 2){
return 1;
} else {
answer = calculate(n - 2) + calculate(n - 1);
return answer;
}
output.value = answer;
}
Don't be complex!
function calculate(n){
if (n < 2){
return 1;
} else {
return calculate(n - 2) + calculate(n - 1);
}
}
<head>
<script src="calculator.js"></script>
</head>
<body>
<input type="number" name="Input" value="" id="userInput" / >
<input type="button" value="Go" onclick="document.getElementById('userAnswer').value=calculate(document.getElementById('userInput').value);" /><br>
<input type="number" name="Answer" id="userAnswer" />
</body>

Output a radio button in a webpage

I'm trying to input the value of the checked radio button as one of a functions parameres (here sign). This is my code:
<!DOCTYPE html>
<html>
<head>
<script src="proj4js/lib/proj4js/lib/proj4js-compressed.js"></script>
</head>
<body>
<script>
function func1 (x,y, sign){
var z=(x+y)*sign
document.getElementById("Z").innerHTML = z;
}
</script>
<form >
first input:<br>
<input id="Y" type="text" y="Y" value=85>
<br>
second input:<br>
<input id="X" type="text" x="X" value=15>
<br>
<input type="radio" name="hem" value=1 id = "N" >north
<input type="radio" name="hem" value=-1 id = "S" >south
The Answer:<br>
<input id="Z" type="text" z="Z" >
<br><br>
</form>
<button type="button" onclick="func1(Number(document.getElementById('X').value),Number(document.getElementById('Y').value), ?? )"> try it </button>
I don't know what to put instead of ?? ? The sign determines if sign is positive or negative.
make input elements as
<form id="demoForm">
first input:<br>
<input id="Y" type="text" value=85>
<br>
second input:<br>
<input id="X" type="text" value=15>
<input type="radio" name="hem" value="1" id="N" >north
<input type="radio" name="hem" value="-1" id ="S" >south
The Answer:<br>
<input id="Z" type="text" z="Z" >
</form>
<script>
function getRadioVal(form, name) {
var val;
// get list of radio buttons with specified name
var radios = form.elements[name];
// loop through list of radio buttons
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked ) { // radio checked?
val = radios[i].value; // if so, hold its value in val
break; // and break out of for loop
}
}
return val; // return value of checked radio or undefined if none checked
}
var val = getRadioVal( document.getElementById('demoForm'), 'hem' );
alert(val); //you can pass this value as parameter
</script>
The simple way would be to write a helper function to collect your paramters and then call your function from this function.
You could use jQuery to get the value of the checked
$('input[name=hem]:checked').val()
Just need to make sure that the form you're using has an id. Then you wouldn't have to pass to the function just get the value directly from the form in your function.
<script>
function func1 (x,y){
var sign = $('input[name=hem]:checked').val();
var z=(x+y)*sign;
document.getElementById("Z").innerHTML = z;
}
</script>
<!DOCTYPE html>
<html>
<head>
<!--
<script src="proj4js/lib/proj4js/lib/proj4js-compressed.js"></script>
-->
</head>
<body>
<form >
first input:<br>
<input id="Y" type="text" y="Y" value=85>
<br>
second input:<br>
<input id="X" type="text" x="X" value=15>
<br>
<input type="radio" name="hem" value="1" id="N" >north</input>
<input type="radio" name="hem" value="-1" id="S" >south </input>
The Answer:<br>
<input id="Z" type="text" z="Z" >
<br><br>
</form>
<button type="button" onclick="func1(Number(document.getElementById('X').value),Number(document.getElementById('Y').value), getAppropriateValue() )"> try it </button>
<script>
function func1 (x,y, sign){
var z=(x+y)*sign
document.getElementById("Z").value = z;
}
function getAppropriateValue(){
var result = 0;
var checkboxN = document.getElementById('N');
var checkboxS = document.getElementById('S');
if(checkboxN && checkboxN.checked) result = 1;
if(checkboxS && checkboxS.checked) result = -1;
return result;
}
</script>
You can entirely take off third param and can output sign based on radio checked property.
<script>
function func1 (x,y) {
var z=(x+y);
if(document.getElementById("N").checked) {
z= z*1;
}elseif(document.getElementById("N").checked) {
z=z*-1;
}
document.getElementById("Z").value = z;
}
</script>

DOM event clearing text values

I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}

Categories

Resources