Making a sum with 4 values and a button - javascript

I'm trying to make a sum of 4 entries in 4 text type and everything seems fine except that when I click the button, it won't set the sum. Like if I enter 1 in each text input, the text input for the sum should show 4. Thanks!
here's my Javascript code :
(function(){
var oForm = document.forms;
oForm[2].querySelector("input[type='button']").
addEventListener("click",
sommeValeur,
false);
}) ()
function sommeValeur() {
var aTxt = document.forms[0].tEx1;
var total = document.forms[0].tEx2;
var txt1 = aTxt[0].value;
var txt2 = aTxt[1].value;
var txt3 = aTxt[2].value;
var txt4 = aTxt[3].value;
total = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4) ;
return true;
}
Here's my html code :
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/form.css" />
</head>
<body>
<section>
<form name="frm1">
<label> Valeur 1:
<input type="text" name="tEx1" />
</label>
<label> Valeur 2:
<input type="text" name="tEx1" />
</label>
<label> Valeur 3:
<input type="text" name="tEx1" />
</label>
<label> Valeur 4:
<input type="text" name="tEx1" />
</label>
</form>
</section>
<section>
<form name="frm2">
<label> Somme:
<input type="text" name="tEx2" />
</label>
</form>
</section>
<section>
<form name="frm3">
<label>
<input type="button"
value="bouton"
name="btn1" /></br>
</label>
</form>
</section>
</body>
<script src="js/exercise4.js"></script>
</html>

It looks like your input for total is in the second form, so you need form[1] and also you need to use total.value to set the value:
var total = document.forms[1].tEx2;
...
total.value = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4) ;
Live example:
(function(){
var oForm = document.forms;
oForm[2].querySelector("input[type='button']").
addEventListener("click",
sommeValeur,
false);
}) ()
function sommeValeur() {
var aTxt = document.forms[0].tEx1;
var total = document.forms[1].tEx2;
var txt1 = aTxt[0].value;
var txt2 = aTxt[1].value;
var txt3 = aTxt[2].value;
var txt4 = aTxt[3].value;
total.value = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4) ;
return true;
}
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/form.css" />
</head>
<body>
<section>
<form name="frm1">
<label> Valeur 1:
<input type="text" name="tEx1" />
</label>
<label> Valeur 2:
<input type="text" name="tEx1" />
</label>
<label> Valeur 3:
<input type="text" name="tEx1" />
</label>
<label> Valeur 4:
<input type="text" name="tEx1" />
</label>
</form>
</section>
<section>
<form name="frm2">
<label> Somme:
<input type="text" name="tEx2" />
</label>
</form>
</section>
<section>
<form name="frm3">
<label>
<input type="button"
value="bouton"
name="btn1" /></br>
</label>
</form>
</section>
</body>
</html>

You are changing the total instance and not the total.value.
In the line total = ...+...+..+...; you are basically replacing the label with the sum. You should set the label text instead: total.value = ...+..+...+...;

Related

parseInt return NaN when take value from input box

i am trying to add 2 number as value from input form. typeof(parseInt(value1)) and typeof(parseInt(value2)) return number
but parseInt(value1)+parseInt(value2) return NaN. please someone explain
var input1 = document.getElementById('num1')
var input2 = document.getElementById('num2')
var value1 = input1.value
var value2 = input2.value
btn.addEventListener('click', myfunc)
function myfunc() {
alert(typeof(parseInt(value1)))
alert(typeof(parseInt(value2)))
alert(parseInt(value1)+parseInt(value2))
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tính toán</title>
</head>
<body>
<form action="">
<div>
<label for="num1">Number 1</label>
<div>
<input type="number" name="num1" id="num1" />
<span class="error" id="errNum1">(*)</span>
</div>
</div>
<div>
<label for="num2">Number 2</label>
<div>
<input type="number" name="num2" id="num2" />
<span class="error" id="errNum2">(*)</span>
</div>
</div>
<div></div>
<div>
<input type="button" value="Tính toán" id="btn" />
</div>
</form>
<script src="js.js"></script>
</body>
</html>
You get the value of the inputs when the page is loaded, so they will always be empty. Instead you want to get the values when the button is clicked.
btn.addEventListener('click', myfunc)
function myfunc() {
var input1 = document.getElementById('num1')
var input2 = document.getElementById('num2')
var value1 = input1.value
var value2 = input2.value
alert(typeof(parseInt(value1)))
alert(typeof(parseInt(value2)))
alert(parseInt(value1)+parseInt(value2))
}
The correct way to do that:
You don't need to use parseInt() on input type= number,
just use valueAsNumber property
const myForm = document.forms['my-form']
myForm.btn.onclick = evt =>
{
console.clear()
console.log(typeof myForm.num1.valueAsNumber)
console.log(typeof myForm.num2.valueAsNumber)
console.log( myForm.num1.valueAsNumber + myForm.num2.valueAsNumber )
}
label
, button {
display : block;
margin : .3em;
}
<form action="" name='my-form'>
<label>
Number 1
<input type="number" name="num1" value="0" >
</label>
<label>
Number 2
<input type="number" name="num2" value="0" >
</label>
<button name="btn" type="button"> Tính toán </button>
</form>

How do I use checkboxes to convert currencies (moneys) from US to whatever the user has checked with Jquery/Inputs

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="Author" content="Micah Cave">
<title>Ice 11</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#convert").click( function() {
var dollarAmount = $('input:text').val();
if ( $("#usa").is(':checked') )
dollarAmount = dollarAmount*1;
if ( $("#russia").is(':checked') )
dollarAmount = dollarAmount * 73.18;
});
});
</script>
</head>
<body>
<h1>Cave</h1>
<h2>Part 1B</h2>
<p>Type in the starting amount (in US dollars) here: <input type="text"></p>
<input type="checkbox" id="usa">US Dollars <br>
<input type="checkbox" id="russia">Russian Ruble <br>
<input type="checkbox" id="france">France Francs <br>
<input type="checkbox" id="japan">Japanese Yen <br>
<input type="button" id="convert" value="Convert currency(s)">
<p id="pasteHere"></p>
</body>
</html>
So I need to take the value that's entered in the input box above, and then if they check off any box(s) to then convert each checked boxs currency from US to whatever was selected, and then print out the results each time using if statements.
you can make a function called convert,when convert button click or checkbox click then call that function.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="Author" content="Micah Cave">
<title>Ice 11</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#convert").click(convert);
$("input:checkbox").click(convert)
});
function convert(){
var dollarAmount = $('input:text').val();
var result = " "
if ( $("#usa").is(':checked') )
result += dollarAmount*1 + ";";
if ( $("#russia").is(':checked') )
result += dollarAmount * 73.18 + ";";
$("#pasteHere").text(result)
}
</script>
</head>
<body>
<h1>Cave</h1>
<h2>Part 1B</h2>
<p>Type in the starting amount (in US dollars) here: <input type="text"></p>
<input type="checkbox" id="usa">US Dollars <br>
<input type="checkbox" id="russia">Russian Ruble <br>
<input type="checkbox" id="france">France Francs <br>
<input type="checkbox" id="japan">Japanese Yen <br>
<input type="button" id="convert" value="Convert currency(s)">
<p id="pasteHere"></p>
</body>
</html>
That is my solution:
$(document).ready(function() {
let selectedCurrencies = [];
$("#convert").click(function() {
let dollarAmount = $('input:text').val();
let checkBoxList = $('input:checked');
let resultText = "";
for (let i = 0; i < checkBoxList.length; i++) {
resultText += "US "+dollarAmount+" dollar =";
switch (checkBoxList[i].id) {
case 'usa':
resultText += dollarAmount * 1;
break;
case "russia":
resultText += dollarAmount * 73.18;
break;
}
resultText+=" "+(checkBoxList[i].nextSibling.textContent)+"<br>";
}
$("#pasteHere").html(resultText);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Cave</h1>
<h2>Part 1B</h2>
<p>Type in the starting amount (in US dollars) here: <input type="text"></p>
<input type="checkbox" id="usa">US Dollars <br>
<input type="checkbox" id="russia">Russian Ruble <br>
<input type="checkbox" id="france">France Francs <br>
<input type="checkbox" id="japan">Japanese Yen <br>
<input type="button" id="convert" value="Convert currency(s)">
<p id="pasteHere"></p>

Javascript how to sum tables

Hello I have a problem with such a task I totally don't know how to get down to it, I hope someone will help me to write an application allowing to calculate the sum and the difference of two 2-dimensional numerical tables. Each of these tables should have 2 lines and 3 columns. Input data - the values of individual array elements - enter the keypads. Present the results on screen, on the same website.
My code is below:
<!DOCTYPE html>
<html lang="pl">
<head>
<title> JavaScript: tablice 2-wymiarowe. </title>
<meta charset="UTF-8">
</head>
<body>
<form id="form1">
Podaj 12 liczb <br />
Pierwsza: <input id="input1" type="text" value="1" /><br />
Druga: <input id="input2" type="text" value="2" /><br />
Trzecia: <input id="input3" type="text" value="3" /><br />
Czwarta: <input id="input4" type="text" value="4" /><br />
piata: <input id="input5" type="text" value="5" /><br />
szosta: <input id="input6" type="text" value="6" /><br />
</form>
<button onclick="przetwarzanie();"> Oblicz </button>
<div id="div1"> </div>
<script>
function przetwarzanie() {
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var input4 = document.getElementById("input4");
var input5 = document.getElementById("input5");
var input6 = document.getElementById("input6");
var div1 = document.getElementById("div1");
var tablica = [];
tablica[0] = Number(input1.value, input2.value, input3.value);
tablica[1] = Number(input4.value, input5.value, input6.value);
suma = tablica[0] + tablica[1];
}
document.getElementById("div1").innerHTML = "Suma = " + suma;
</script>
</body>
</html>
First of all the last line of your script is outside the function while it uses a variable that is inside, this will not work but can easily be fixed by moving the line inside the function.
The second issue is that Number converts a string to a number. It does not sum them up. Instead move each input value to it's own Number function and add them together with the + sign.
For the difference in the two numbers you can just subtract one from the other. With Math.abs() we turn the number into a positive. This way we don't need to think about which of the two numbers is higher.
<!DOCTYPE html>
<html lang="pl">
<head>
<title> JavaScript: tablice 2-wymiarowe. </title>
<meta charset="UTF-8">
</head>
<body>
<form id="form1">
Podaj 12 liczb <br />
Pierwsza: <input id="input1" type="text" value="1" /><br />
Druga: <input id="input2" type="text" value="2" /><br />
Trzecia: <input id="input3" type="text" value="3" /><br />
Czwarta: <input id="input4" type="text" value="4" /><br />
piata: <input id="input5" type="text" value="5" /><br />
szosta: <input id="input6" type="text" value="6" /><br />
</form>
<button onclick="przetwarzanie();"> Oblicz </button>
<div id="div1"> </div>
<div id="div2"> </div>
<script>
function przetwarzanie() {
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var input4 = document.getElementById("input4");
var input5 = document.getElementById("input5");
var input6 = document.getElementById("input6");
var div1 = document.getElementById("div1");
var tablica = [];
tablica[0] = Number(input1.value) + Number(input2.value) + Number(input3.value);
tablica[1] = Number(input4.value) + Number(input5.value) + Number(input6.value);
var suma = tablica[0] + tablica[1];
var roznica = Math.abs(tablica[0] - tablica[1]);
document.getElementById("div1").innerHTML = "Suma = " + suma;
document.getElementById("div2").innerHTML = "Różnica = " + roznica;
}
</script>
</body>
</html>
Suma undefined means you never created a variable and then you used it which caused the error below code is working just put all your code inside onclick function so when clicked it calculates and add it to html.
<!DOCTYPE html>
<html lang="pl">
<head>
<title> JavaScript: tablice 2-wymiarowe. </title>
<meta charset="UTF-8">
</head>
<body>
<form id="form1">
Podaj 12 liczb <br />
Pierwsza: <input id="input1" type="text" value="1" /><br />
Druga: <input id="input2" type="text" value="2" /><br />
Trzecia: <input id="input3" type="text" value="3" /><br />
Czwarta: <input id="input4" type="text" value="4" /><br />
piata: <input id="input5" type="text" value="5" /><br />
szosta: <input id="input6" type="text" value="6" /><br />
</form>
<button onclick="przetwarzanie();"> Oblicz </button>
<div id="div1"> </div>
<script>
function przetwarzanie() {
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var input4 = document.getElementById("input4");
var input5 = document.getElementById("input5");
var input6 = document.getElementById("input6");
var div1 = document.getElementById("div1");
var tablica = [];
tablica[0] = Number(input1.value, input2.value, input3.value);
tablica[1] = Number(input4.value, input5.value, input6.value);
let suma = tablica[0] + tablica[1];
document.getElementById("div1").innerHTML = "Suma = " + suma;
}
</script>
</body>
</html>

Jquery event handling when a checkbox is clicked

edit Updated full code :
I'm working on my first Javascript case i'm stuck here :
I have the following :
$(document).ready(function()
{
$('input, select').on('focus' ,swapPersonClass);
//Blur = Bind an event handler to the “blur” JavaScript event, or trigger that event on an element.
$('input, select').on("change", updateCart);
}
);
// Functions
var swapPersonClass = function()
{
var expression = $(this).attr('id');
switch(expression)
{
case "fullname":
break;
case "email":
$("#arm").removeClass().addClass("pointemail");
break;
case "countpizzas":
$("#arm").removeClass().addClass("pointamount");
break;
default:
$("#arm").removeClass().addClass("pointothers");
}
};
var updateCart = function () {
var change = $(this).attr('id');
console.log(change);
$('input, select').each(function ()
{
switch (change)
{
case "fullname":
$("#displayname").text($('#fullname').val() + ',');
break;
case "countpizzas":
aantalpizzas = $("#countpizzas").val();
if (aantalpizzas > 1) {
$('.plural').show();
} else {
$('.plural').hide();
};
$("#displayamount").text(aantalpizzas);
console.log(aantalpizzas);
break;
case "pizzatype":
PrijsPizza = $("#pizzatype option:selected").data("price");
console.log(PrijsPizza);
break;
case "YesOption":
$("#toppings").show();
break;
case "NoOption":
$("#toppings").hide();
break;
case "toppings":
updateTopping();
break;
};
$("#currenttotal").text(aantalpizzas * PrijsPizza );
});
};
var updateTopping = function ()
{
$(".chk_topping").change(function()
{
var selected_topping = $(this).attr('data-value');
switch(selected_topping)
{
case "salami":
$("#currenttotal").text(aantalpizzas * PrijsPizza );
PrijsTopping += 0.30;
break
}
});
};
var PrijsTopping = 0.30;
var aantalpizzas = 0;
var PrijsPizza = 0;
<!DOCTYPE html>
<html>
<head>
<title>Forms</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Lobster">
<link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="assets/css/reset.css"/>
<link rel="stylesheet" href="assets/css/screen.css" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="container">
<header>
<h1>Pizza Palace</h1>
</header>
<aside>
<h2><span>Order details</span></h2>
<div id="total">
<p>Your current order total: € <strong id="currenttotal">0</strong></p>
</div>
<p><strong id="displayname"></strong> you are ordering <strong id="displayamount"></strong> pizza<span
class="plural">s</span></p>
<h3>Chosen toppings:</h3>
<div id="toppingmessage">
<p>No toppings selected</p>
<ul>
<li class="hide">Salami</li>
<li class="hide">Olives</li>
<li class="hide">Ansjovis</li>
</ul>
</div>
<h3>Your discount: </h3>
<p id="displaydiscount"></p>
</aside>
<form action="#" method="post">
<figure id="arm"></figure>
<figure id="face"></figure>
<fieldset class="personbody">
<form>
<div>
<label for="fullname">Full Name
<input id="fullname" name="fullnames" type="text" required autofocus>
</label>
</div>
<div>
<label for="email">Email
<input id="email" name="email" type="email" placeholder="Enter Your email" required>
</label>
</div>
<div>
<label for="howmany">How many pizzas would you like?<br><br>
<input id="countpizzas" name="countpizzas" type="number" min="1" max="3" step="1" value="0" required>
</label>
</div>
<div>
<label for="pizzatype">Which type of pizza would you like ? <br>
<select id="pizzatype"name="pizzatype">
<option data-price="4" value="S">Small</option>
<option data-price="5.5" value="M">Medium</option>
<option data-price="7" value="L">Large</option>
</select>
</label>
</div>
<div>
<label for="extratopping">Would you like extra topping? <br>
<input id="YesOption" name="ExtraTopping" type="radio"> Yes
<input id="NoOption" name="ExtraTopping" type="radio"> No
</label>
</div>
<div class="hide" id="toppings">
<label for="toppings">Which toppings would you like?</label>
<input type="checkbox" class="chk_topping" data-value="salami"> Salami
<input type="checkbox" class="chk_topping" data-value="olives"> Olives
<input type="checkbox" class="chk_topping" data-value="ansjovis"> Ansjovis
</div>
<div>
<label for="deliverydate">When do you want the pizza<span class="plural">s</span> to be delivered?
<input id="delivery" name="delivery" type="date" required > </label>
<label for="deliverytime">
<input id="Time" name="Time" type="time" required> </label>
</div>
<label for="discountcode">Do you have a discount code?
<input id="DiscountCode" name="DiscountCode" type="text" pattern="[1-9]{1}-[A-Z]{3}" title="The discount code should be a digit followed by a dash and then 3 uppercase letters" required>
</label>
</div>
</form>
<input type="submit" value="Place your order" name="placeorder"/>
</fieldset>
</form>
<footer><p>Graphics courtesy of © Basecamp </p></footer>
</div>
<script type='text/javascript' src='assets/js/jquery.js'></script>
<script type='text/javascript' src='assets/js/script.js'></script>
</body>
</html>
Why my checkboxes keep telling me it's undefined when selecting them ?
I'm realy not good at javascript so my code will probably be sh*t
Try this
var selected_topping = $(this).data('value');
http://jsfiddle.net/f4Lghy6p/
Found it.
i'm searching for a specefic ID in my select en input fields :
$('input, select').on("change", updateCart);
My checkboxes are located in a DIV with an input fields which don't have an ID.

multiple forms with javascript

I am trying to show forms according to user input in the text box but it is showing it one time only...please help...
index.html:
<html>
<head>
<script type="text/javascript" src="demo1.js"></script>
</head>
<body>
<form name="su">
<input type="text" name="tt" onkeyup="javascript:toggleFormVisibility();" id="sub"/> </a>
</form>
<form id="subscribe_frm" style="display:none">
NAME:<input type="text" name="text">
EMAIL:<input type="text" name="text">
PASSWORD:<input type="text" name="text">
</form>
demo.js:
function toggleFormVisibility()
{
var txt = document.getElementById('sub').value;
for(var i=0;i<txt;i++)
{
var frm_element = document.getElementById('subscribe_frm');
var vis = frm_element.style;
vis.display = 'block';
}
}
A bit of a guess, but I think you are trying to create multiple copies of your form. Try this out:
http://jsfiddle.net/QnrM9/
JS
function toggleFormVisibility() {
var txt = document.getElementById('sub').value;
var neededChildren = txt.length - document.getElementById('form_container').children.length + 1;
for (var i = 0; i < neededChildren; i++) {
var frm_element = document.getElementById('subscribe_frm').cloneNode(true);
var vis = frm_element.style;
vis['display'] = 'block';
document.getElementById("form_container").appendChild(frm_element);
}
}
document.getElementById('sub').addEventListener('keyup', toggleFormVisibility);
HTML
<form name="su">
<input type="text" name="tt" id="sub" />
</form>
<div id="form_container">
<form id="subscribe_frm" style="display:none">NAME:
<input type="text" name="text" />EMAIL:
<input type="text" name="text" />PASSWORD:
<input type="text" name="text" />
</form>
</div>

Categories