I am trying to pass on JQuery values to hidden textboxes (to send as a form later) as well as divs t
hat displays on the front end. I also want to tally these items as the value is passed to them. I have Frankensteined this bit of code which passes on the value to the the input boxes and the divs and it also tallies them onclick. I am just struggling to get the sum to display in #total_div. Can anyone point me in the right direction please?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#my_div').click(function() {
$('#my_value_1').val("100");
$('#my_value_1_div').html( "100" );
$('#my_div').click(addNumbers('total'));
});
});
$(document).ready(function(){
$('#my_div_2').click(function() {
$('#my_value_2').val("200");
$('#my_value_2_div').html( "200" );
$('#my_div_2').click(addNumbers('total'));
});
});
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
</script>
<h2>My pretty front end</h2>
<div id="my_div">ADD THIS VALUE 1</div>
<div id="my_div_2">ADD THIS VALUE 2</div>
VALUE 1: <div id="my_value_1_div">VALUE 1 GOES HERE</div>
VALUE 2: <div id="my_value_2_div">VALUE 2 GOES HERE</div>
TOTAL: <div id="total_div">SUM MUST GO HERE</div>
<h2>My hidden Form</h2>
Value 1: <input type="text" id="my_value_1" name="my_value_1" value="0"/>
Value 2: <input type="text" id="my_value_2" name="my_value_2" value="0"/>
<input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
Total: <input type="text" id="total" name="total" value=""/>
EDIT
Ok so thanks to the advice I got the above working but now I need to clear the amounts. This is what I have done, it is almost there I think but I'm getting the incorrect sum.
$('#clear').click(function() {
$('#my_value_1').val('0');
$('#my_value_1_div').html( "0" );
$('#clear').click(minusNumbers('total'));
});
function minusNumbers()
{
var minval1 = parseInt(document.getElementById("my_value_1").value);
var minval2 = parseInt(document.getElementById("total").value);
var minansD = document.getElementById("total");
minansD.value = minval2 - minval1;
$('#total_div').text(minansD.value);
}
Update #total_div text in addNumber function as,
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
$('#total_div').text(ansD.value);
}
Demo
replace:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
with:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD = val1 + val2;
$('#total').val(ansD);
}
click(addNumbers('total')); first calls addNumbers with an unused parameter 'total' then gets the return value of addNumbers (null or undefined) and sets that as the click() handler for the next click.
I think you probably meant
$('#my_div').click(addNumbers);
that means, "run the addNumbers function, defined below, next time I click my_div".
or just
addNumbers();
that means, "run the addNumbers function now" (at the first click)
Note though that when you click and call addNumbers, one of the numbers may not yet be copied, so you would be adding 100+"" or ""+200 so you really have to think about what you want to do.
Related
I have an input text and a button where a I put a number and storage this value in a Cookie using js-cookie clicking a button.
<input id="number" type="text" value="0">
<button id="send" type="button">SEND</button>
I want to sum each time I enter a number and show the result in an alert, so I tried in this way:
Jquery:
$("#number").keypress(function(e){
if(e.keyCode==13){
$("#send").click();
}
});
$("#send").click(function(){
var number= 0;
number+= parseInt($("#number").val(),10);
Cookies.set("numw", number);
});
var numw = Cookies.get("numw");
alert("Total: "+numw);
But this still showing the first number I sent.
I would like some help.
All you need is to add the number like:
$("#send").click(function(){
//var number= 0;
var numwTemp = Cookies.get("numw");
//number = parseInt($("#number").val(),10)) + parseInt(numwTemp, 10);
var number = parseInt($("#number").val(),10)) + parseInt(numwTemp || "0", 10);
Cookies.set("numw", number);
});
var numw = Cookies.get("numw");
alert("Total: "+numw);
I want every time when user enter number ,print the new one + old one in console
here is html script
<input type="number"value=""/>
<button>click</button>
my jquery code
$("button").click(function (){
var x = $("input").val();
x+=x;
console.log(x);
});
You have to initialize the value outside somewhere to keep its state.
html
<input type="number" id="inp" value=""/>
<button>click</button>
js
var x = 0;
$("button").click(function (){
var y = parseInt($("#inp").val());
x+=y;
console.log(x);
});
hope this will help to you. refer the working demo.
var thevalue = 0;
$("#click").click(function(){
$("#display").text("The Value is :");
var theinput_value = parseInt($("#num").val());
thevalue += theinput_value;
$("#display").append(thevalue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Enter the nubmer : <input type="number" id="num"><button id="click">Click on me !</button>
<br>
<p id="display">The Value is :</p>
You just need to make sure x is a global variable so you can save it's value and used each time the click handler is triggered.
I added input casting to avoid string concatenation when using the addition assignment operator.
var x = 0;
$("button").click(function (){
// Get the input
var current_input = parseInt($("input").val());
// If input is not a number set it to 0
if (isNaN(current_input)) current_input = 0;
// Add the input to x
x+=current_input;
// Display it
console.log(x);
});
I constructed a calculation form out of different modules and got it to work except for 1 element.
The overall calculation is build up as (value + value = total), and the values are all regular numbers.
However, the last bit I added is a 'percentage'-value which is 10% of the first value in the form. So as an example:
Value 1 = 50,
Percent value 2 = 5 (10% of value 1),
Total = 55
In my code this looks as follows:
var NonTrans_prices = new Array();
NonTrans_prices["NoneNon"] = 0;
NonTrans_prices["LemonNon"] = 5994;
NonTrans_prices["CustardNon"] = 7076;
function NonTrans() {
var NonTransPrice = 0;
var theForm = document.forms["GRANADANEO"];
var selectedFilling = theForm.elements["NonTrans"];
NonTransPrice = NonTrans_prices[selectedFilling.value];
return NonTransPrice;
}
var price = NonTrans_prices;
var percentage = 10;
var costs = (price * percentage) / 100;
var optionprice = price + percentage;
function optionprice1() {
var inscriptionPrice = 0;
var theForm = document.forms["GRANADANEO"];
var optionprice = theForm.elements["optionprice"];
if (optionprice.checked == true) {
inscriptionPrice = optionprice.value;
}
return inscriptionPrice;
}
function calculateTotal() {
var cakePrice = NonTrans() + optionprice1();
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Total Price: " + cakePrice + " \u20ac";
}
*The NonTransPrice is connected to a dropdown box, and the optionprice1 is connected to a checkbox.
As soon as I tick the checkbox containing the 10% value, the letters "on" are added to the total price. What's going wrong?
**Sorry forgot to post the entire code so that you guys/girls can test: https://jsfiddle.net/6a55tm4j/
For some reason it doesn't show the total value in jsfiddle, on the live website I am testing on it does so that's not really a problem I am facing live.
Live link: http://axesseurope.be/appalacarte/Calculator/axess_calculator.html
This is the HTML code containing the parts affected by the .js code:
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="GRANADANEO" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<table><tr><td>
<label >NonTrans</label>
<select id="NonTrans" name='NonTrans' onchange="calculateTotal()">
<option value="NoneNon">Select Dimensions</option>
<option value="LemonNon">3,00 6,40 0,85</option>
<option value="CustardNon">3,00 7,50 0,85</option>
</select>
</td></tr></table>
<hr>
<br/>
<label>Granada Neo Opties Algemeen</label>
<p>
<input type="checkbox" id="optionprice" name='optionprice' onclick="calculateTotal()" />
<label for='optionprice' class="inlinelabel">optionprice</label>
</p>
<p>
<input type="checkbox" id="SchuifdeurVoorzijde" name='SchuifdeurVoorzijde' onclick="calculateTotal()" />
<label for='SchuifdeurVoorzijde' class="inlinelabel">Schuifdeur in voorzijde</label>
</p>
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
In the end with the help of Scott Marcus this was the solution:
function optionprice1()
{
var chkOptionPrice = document.getElementById("optionprice");
var theForm = document.forms["GRANADANEO"];
var selectedFilling = theForm.elements["NonTrans"];
var lstNonTransValue = NonTrans_prices[selectedFilling.value];
var inscriptionPrice = 0;
if(optionprice.checked === true){
// Look up the price in the array that matches the dropdown list's value
var price = NonTrans_prices[selectedFilling.value];
// Do the math to calculate 10% of the original price
var percentage = 10;
inscriptionPrice = (price * percentage) / 100;
}
// finally we return the inscriptionPrice
return inscriptionPrice;
}
Checkboxes have a value of "on" when they are selected. Ensure that your checkboxes include a value attribute that contains the meaningful data they represent. For example:
<input type="checkbox" id="chkSomeId" name="chkSomeID"
value="someValueToBeWhenChecked">
This is true of radio buttons as well.
So, in your code, this line:
inscriptionPrice = optionprice.value
is most-likely accessing the value of either a checkbox or radio button that does not have an explicit value set for it, but is checked.
Also, remember that all values pulled from HTML come into JavaScript as strings, so if you need to do math with those values, you'll want to use parseInt() and parseFloat().
UPDATE: now that you have posted your HTML, I see this:
<input type="checkbox" id="optionprice" name='optionprice' onclick="calculateTotal()" />
which is exactly what I suspected. My above answer will correct the problem. That checkbox needs a value set for it.
UPDATE:
In your following code:
//Add percentage
var price = NonTrans_prices;
var percentage = 10;
var costs = (price * percentage) / 100;
var optionprice = price + percentage;
//Add percentage
function optionprice1()
{
var inscriptionPrice=0;
//Get a refernce to the form id="GRANADANEO"
var theForm = document.forms["GRANADANEO"];
//Get a reference to the checkbox id="optionprice"
var optionprice = theForm.elements["optionprice"];
//If they checked the box set inscriptionPrice to 20
if(optionprice.checked==true){
inscriptionPrice=optionprice.value;
}
//finally we return the inscriptionPrice
return inscriptionPrice;
}
I think that you should take the 4 var lines and include them in the function.
I think that the first line: var price = NonTrans_prices; is incorrect, because it sets the variable price to the actual array of NonTrans prices, rather than looking up a particular price, which would be:
var price = NonTrans_prices[document.getElementById("nonTransList").value];
Then, your problem is that if the optionPrice checkbox is checked, you are trying to access the value of the checkbox, which (as I've said) doesn't explicitly exist, so you get "on" (because the checkbox is checked). What you should be doing is setting the price to result of the 10% calculation that was just done on the line above. So the final function looks like this:
function optionprice1()
{
var chkOptionPrice = document.getElementById("optionprice");
var lstNonTransValue = document.getElementById(NonTrans).value;
var inscriptionPrice = 0;
if(optionprice.checked === true){
// Look up the price in the array that matches the dropdown list's value
var price = NonTrans_prices[lstNonTransValue];
// Do the math to calculate 10% of the original price
var percentage = 10;
inscriptionPrice = (price * percentage) / 100;;
}
// finally we return the inscriptionPrice
return inscriptionPrice;
}
You were close, but the thing that, I think, tripped you up was that you created a variable with the same name as your checkbox and after doing the calculation, you should have been trying to get the value of your variable, but you were trying to get the value of the checkbox, which isn't where the answer was.
I hope that I've understood what you wanted correctly, but even if my algorithm is off, I hope you can see that you don't want to be using the value of the checkbox to get your answer, since it doesn't store any value.
Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim
I have a form that requires three inputs as follows:
<form>
<input name="mn"
type="number"
min="1"
value="1">
<input name="mx"
type="number"
min="2"
value="10">
<input name="step"
type="number"
min="1"
value="1">
<input onclick="myfunc()"
type="submit"
value="calculate">
</form>
all i require is to be able to access the three fields directly in javascript. I do not need to pass the information anywhere else.
Could anyone point me in the right direction? I have read examples where there has been one input, but not multiple.
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")
var mx = document.getElementsByName("mx")
var step = document.getElementsByName("step")
alert((mn + mx) / step)
}
</script>
Give your form an id like so
<form id="myForm">
The other thing to watch out for is that the is that the value attribute is a string so adding the two values concatenates them rather than summing them.
Try instead
var frm = document.forms["myForm"];
var _mn = parseInt( frm["mn"].value );
var _mx = parseInt( frm["mx"].value );
var _step = parseInt( frm["step"].value );
var result = ( _mn + _mx ) / _step;
I'd start with giving each input an id then i could use:
var min = document.getElementById('mn')
and so on. To access the value you simply would call
min.value
Also there is no point in removing the i from min and the a from max. That is not optimized just hard to read and understand.
Try this:
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")[0].value;
var mx = document.getElementsByName("mx")[0].value;
var step = document.getElementsByName("step")[0].value;
var top = mn / mx;
alert(top / step);
}
</script>
if u need to access to the values of the inputs change your code to:
function myfunc() {
var mn = document.getElementsByName("mn")[0];
var mx = document.getElementsByName("mx")[0];
var step = document.getElementsByName("step")[0];
// you may need to validate your values here, like step.value != 0
alert((mn.value + mx.value) / step.value)
}