I have three DIV whose content are integer values and are updated frequently from another source. My main idea here was to take the content of the three divs parse it into float or integer , add them and display the total in another div. I am looking forward to handle the content in div using a onchange() function, because the the content in them will be changing frequently. Below is my code, its currently not working, i will really appreciate it if you give me a hand of help with this.
The content in this divs will be frequently updated using a text input, you can create a text inout that manipulates the first div then displays the whole sum
Thanks in advance.
<script>
function total() {
var value1 = parseFloat($('#div1').innerHTML ()) || 0;
var value2 = parseFloat($('#div2').innerHTML ()) || 0;
var value3 = parseFloat($('#div1').innerHTML ()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body >
<div id="mywraper">
<div id="div1" onchange="total()">
4
</div>
<div id="div2" onchange="total()">
5
</div>
<div id="div2" onchange="total()">
6
</div>
</div>
<div id="total_div">
Total $<span id="total"></span>
</div>
</body>
</html>
Use this html()
<script>
function total() {
var value1 = parseFloat($('#div1').html()) || 0;
var value2 = parseFloat($('#div2').html()) || 0;
var value3 = parseFloat($('#div1').html()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
Try this:
function total() {
// fetch text using 'text' method and then convert string into number using '+' operator
var value1 = +$('#div1').text() || 0;
var value2 = +$('#div1').text() || 0;
var value3 = +$('#div1').text() || 0;
var total = value1 + value2 + value3;
$('#total').html(total);
}
http://jsfiddle.net/uxajjk1b/2/
Use text() instead of innerHTML, like so:
<script>
function total() {
var value1 = parseFloat($('#div1').text()) || 0;
var value2 = parseFloat($('#div2').text()) || 0;
var value3 = parseFloat($('#div1').text()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
I didn't really want to answer, as this might be difficult to solve due to the fact that we have no idea how the values are updated in the first place. However, I ended up doing relatively extensive example, so here we are.
So as mentioned before, onChange requires user input or action to detect any change. So that means your total() would only trigger once when the page is loaded ( assuming it's placed right before </body> ).
The best method would be to also stick the total() inside the original function that changes the values inside the html elements. This way total() is also triggered each time.
I couldn't resist making the total() more dynamic. This way, if you add or remove those child divs, the javascript won't need to be updated.
Here's a link to the original jsfiddle
var parentContainer = $('#mywraper');
function total() {
var values = {}; // Optional****
var total = 0;
// Loops through parent containers children ( in this case div elements ).
parentContainer.children().text(function( i, val ) {
var value = parseInt( val );
// Creates a variable where the variable name is based on the current elements index and value is based on the text inside the element.
values[ 'child_' + (i+1) ] = value; // Optional****
// Sums up all the values
total += value;
});
// The optional lines enable you independently check each value, for example:
// console.log( values.child_1 )
// Push total into the #total element.
$('#total').html( total );
}
total();
Here's an example where the values are updated with a click event. So what you do is just add the total() inside the click event as well.
function total() {
var parentContainer = $('#mywraper'),
total = 0;
parentContainer.children().text(function( i, val ) {
total += parseInt( val );
});
$('#total').html( total );
}
total();
$('#updateBtn').on("click", function() {
$('#mywraper').children().text(function( i, val ) {
return parseInt( val ) + 1;
});
total();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mywraper">
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div id="total_div">
Total $<span id="total"></span>
</div>
<button id="updateBtn">Update values</button>
Related
Actually, I want to get integer value this is working when i'm inserting value suppose i insert value 4+5 in input then I'm getting it in my result then I'm gettting it in another div with result like if I get 4+5 then it should be 9.
But i'm getting [object Object]
What is wrong in my code?
$(document).ready(function(){
$('button').click(function(){
var oldValue;
var getValue;
var boxValue;
oldValue = $('.box').text();
getValue = $('.getValue').val();
boxValue = $('.box').text(oldValue + getValue);
$('.finalResult').text(boxValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button</button>
<input type="text" class="getValue">
<div class="box"></div>
<div class="finalResult"></div>
$(document).ready(function(){
$('button').click(function(){
var oldValue;
var getValue;
var boxValue;
oldValue = $('.box').text();
getValue = $('.getValue').val();
boxValue = $('.box').text(oldValue + getValue);
$('.finalResult').text(Number(oldValue || '0') + eval(getValue));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button</button>
<input type="text" class="getValue">
<div class="box"></div>
<div class="finalResult"></div>
$(document).ready(function(){
$('button').click(function(){
var oldValue;
var getValue;
var boxValue;
oldValue = $('.box').text();
getValue = $('.getValue').val();
if(!isNaN(oldValue) && !isNaN(getValue) )
{
boxValue = $('.box').text(oldValue + getValue);// in this line you are setting a value and assignig it to boxValue
$('.finalResult').text(boxValue.text());//I am replacing this line
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button</button>
<input type="text" class="getValue">
<div class="box">0</div>
<div class="finalResult"></div>
see this fiddle
I'm not quite sure what your ultimate goal is, but the [Object Object] occurs because you are placing the jQuery representation of .box into the DOM, which is an object.
Try changing these lines ...
oldValue = +$('.box').text() || 0;
getValue = +$('.getValue').val();
$('.finalResult').text(boxValue.text());
The first two lines are one way to ensure you have a number; the last places the correct "text".
You are getting [objec object] because you are actually trying to set an object in the div, below see the problem line. What you are doing is that you calculate the some and set the result .finalResult div but you are actually assigning the div to a variable and jquery is treating that variable as an object
$(document).ready(function(){
$('button').click(function(){
var oldValue;
var getValue;
var boxValue;
oldValue = $('.box').text();
getValue = $('.getValue').val();
boxValue = $('.box').text(oldValue + getValue); //<-- problem
$('.finalResult').text(boxValue);
});
});
change the following line
$('.finalResult').text(boxValue);
with this one
$('.finalResult').text(boxValue.text());
I might be missing the elephant in the room here, but I can't figure this out.
What I want to do, add Y amount to variable X each time a button is clicked. Y is passed through the onClick function.
addStat: function(button, amount, price) {
var curPrice = price;
var priceHtml = $(button).closest("tr").find('.price');
curPrice += price;
$(priceHtml).text(curPrice);
},
This is what I have, but I have a feeling that I'd Need to set a value to current price, outside the function maybe? I tried but then It'd always reset on each button press.
Any idea/suggestion is welcome. I'm kinda of new to JS. Just learning.
One method I know would work, if I'd get the value of the price HTML element. But the issue with that, is that it can be edited with chrome inspect.
You just need to get the current price value using priceHtml.text() and assign it to your curPrice variable.
Try this:
var priceHtml = $(button).closest("tr").find('.price');
var curPrice = parseFloat(priceHtml.text())||0;
curPrice += price;
priceHtml.text(curPrice);
I tried to reduce what you're trying to do to just a minimum example. From your question, it sounds like you're trying to do four things on a click:
take in the text value of an element
coerce that value to a number
double the number
write the new value to the element
You don't have to move the curPrice var outside of the function. It doesn't matter that you redeclare it on each click, because you're immediately doubling it against itself. And you'll want to parse the incoming text to a number with parseInt, otherwise javascript will assume you're trying to do string concatenation:
function addStat(event) {
var curPrice = parseInt(event.target.textContent, 10);
curPrice += curPrice;
$(event.target).text(curPrice);
}
$('.price').click(addStat)
.price {
background-color: #ace;
height: 25px;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">1</div>
<div class="price">3</div>
You have to set your let curPrice = 0; outside the function, on top of your code. Then you can simply use curPrice += parseFloat(price); inside the function. That prevent the wrong overwriting value of curPrice.
EDIT -> Example:
let curPrice = 0;
function updatePrice(button, amount, price) {
if(!isNaN(price)) {
curPrice += price;
return $(button).find('.price').text(curPrice.toFixed(2));
}
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="updatePrice(this, 10.00, 10.00)">
<span class="price">0.00</span>
</button>
<button onclick="updatePrice(this, 10.00, 'isNaN')">
<span class="price">Not working!</span>
</button>
And use let variable; instead of var variable;
Another example:
function updatePrice(button, amount, price) {
//Find the .price inside the clicked button
let $price = $(button).find('.price');
//Test if price is numeric
if(!isNaN(price)) {
//If is numeric retrive the current price and add the price
let newPrice = parseFloat($price.text()) + parseFloat(price);
//Return the new price and print it on .price inside the button
return $price.text(newPrice.toFixed(2)); // .toFixed(2) return 2 decimal.
}
//If price is not numeric return false
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- price is numeric so it works -->
<button onclick="updatePrice(this, 10.00, 10.00)">
<span class="price">10.00</span>
</button>
<!-- price is not numeric so the function return false -->
<button onclick="updatePrice(this, 10.00, 'not numeric')">
<span class="price">10.00 (not working)</span>
</button>
Good luck!
This question already has an answer here:
Getting an empty value with val()
(1 answer)
Closed 7 years ago.
I am trying to add two values together, and append that value to a div. The value is saying "0" when value1 = 30 and value2 = 3.
<script>
jQuery(document).ready(function( $ ) {
var value1 = $(".value1").val();
var value2 = $(".value2").val();
var sum = addnumbers(value1,value2);
$(".sum").append(sum);
function addnumbers(value1,value2){
var sum=Number(value1)+Number(value2);
return sum;
};
});
</script>
Html is pretty evident:
<div class="value1">30</div>
<div class="value2">3</div>
<div class="sum"></div>
You should do
var value1 = $(".value1").text(); // or html (in your html both are same)
var value2 = $(".value2").text();
div doesn't have value attribute.
so either use .html() or .text()
with divs (in your case) you need to use .text() .. .val() with inputs , select
var value1 = $(".value1").text();
var value2 = $(".value2").text();
.val() only works for inputs. For any other HTML element to get the html within you can use .html() or .text()
HTML
<div class="value1">30</div>
<div class="value2">3</div>
<div class="sum"></div>
JS
$(document).ready(function() {
$(".sum").append(addnumbers($(".value1").html(),$(".value2").html()));
});
function addnumbers(value1,value2){
return (Number(value1)+Number(value2));
};
JSFiddle
I've made you a fiddle
Code:
jQuery(document).ready(function( $ ) {
var value1 = $(".value1").html();
var value2 = $(".value2").html();
function addnumbers(value1,value2){
var sum = parseInt(value1) + parseInt(value2);
return sum;
};
var sum = addnumbers(value1,value2);
$(".sum").append(sum);
});
<div class='value1'>2</div>
<div class='value2'>4</div>
<div class='sum'></div>
I have a div structure like below
<div id=main">
<input type="hidden" id="people_0_1_0" value="12"/>
<input type="hidden" id="people_0_1_1" value="12"/>
</div>
Now how to add all hidden input values in a variable. Thanks
Using Jquery's map function
var myArray = $('#main input').map(function(){
return $(this).val();
}).get();
It will collect all input's values(12 and 12 in this case) to array variable.
See jsfiddle http://jsfiddle.net/GkXUS/1/
If you want to get sum of values you can do the following
var total = 0;
$.each(myArray,function() {
total += parseInt(this,10);
});
var total = 0;
$('#main input[id^="people_"]').each(function(){
total += parseInt(this.value, 10);
});
Note that I am using attribute starts with selector to find all the input elements whose id starts with people_.
total will give you the total of all the input elements value.
I guess you want this:
var hidden_value = new Array();
var hiddens = document.getElementById( "main" ).childNodes;
for( i = 0 ; i < hiddens.length ; i++ ){
hidden_value.push( hiddens[ i ].value );
}
You could try something like this:
var peopleData = $("#main input[type=hidden]").serializeArray();
Putting values in a variable does not make sense. You can insert the values in a Array and perform your required operation
Using Plain Javascript
var els=document.getElementById('main').childNodes;
var allVal=[];
for(i=0; i<els.length-1; i++)
{
if(els[i].nodeType != 3 && els[i].type=="hidden") allVal.push(els[i].value);
}
console.log(allVal); // the array
console.log(allVal[0]); // first value
An example is here.
I've an html page which has many dynamically created input boxes. The number of text boxes vary each time.
I want to calculate the sum of the numbers the user has entered, and disply it. When the user delete one number the sum should auto calculate.
How can i do it with javascript?
Thanks
In jQuery something like this should work with a few assumptions:
$('.toAdd').live('change', function() {
var total = 0;
$('.toAdd').each(function () {
total += $(this).val();
});
$('#total').val(total);
});
The assumptions being that your input fields all have the class 'toAdd' and that your final input field has an ID of 'total'.
In pure JS:
var elems = document.getElementsByClassName('toAdd');
var myLength = elems.length,
total = 0;
for (var i = 0; i < myLength; ++i) {
total += elems[i].value;
}
document.getElementById('total').value = total;
Let me elaborate when I review my notes but here is a high level answer that I believe will work... (My Java Script is very rusty)...
Make the input boxes share an attribute (or use tag) so you can get a collection to walk through no matter the size... Then on the onkeyup event on every input call this function that will sum the totals. Put the result into another entry with the ID you know beforehand...
You will have to validate input because if one of them is not a number then the total will also be "NAN"
Okay here is a complete working example you can build off of that I just threw together: It obviously needs a great deal of polishing on your end...
<html>
<head>
<script language="javascript">
function AddInputs()
{
var total = 0;
var coll = document.getElementsByTagName("input")
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById("Display");
Display.innerHTML = total;
}
</script>
</head>
<body>
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<span id="Display"></span>
</body>
</html>