JQuery Adding the values of 2 divs into a third div - javascript

I have 3 divs with numbers in each...
<div id="one">1</div>
<div id="two">5</div>
<div id="total">0</div>
What I need to do for example is:
If #one is click then Add the values of #one and #two and update it on #total
So, in the case above total would look like this:
<div id="total">6</div>

HTML:
<div id="one">1</div>
<div id="two">5</div>
<div id="total">0</div>
<input id="btn-calculate" type="button" value="Calculate" />
JavaScript:
var one = document.getElementById('one'),
two = document.getElementById('two'),
total = document.getElementById('total');
document.getElementById('btn-calculate').onclick = function() {
total.innerHTML = parseInt(one.innerHTML) + parseInt(two.innerHTML);
};
Demo

$('#one').click(function(){
$("#total").text(
parseFloat($(this).text()) +
parseFloat($("#two").text())
);
});

​$("#one")​.click(function(){
$("#total").html(parseInt($(this).text()) + parseInt($("#two").text()))
})​
http://jsfiddle.net/daniilr/G4Snm/

Try this,
Live Demo
$("#one").click(function() {
$('#total').text(parseFloat($('#one').text()) + parseFloat($('#two').text()));
});​

Related

Calculate sum on-click and append total?

I want to calculate numbers in some DIV boxes and append the total in another DIV.
How can I make this work on-click of the box class as another function adds the values to the box dynamically?
I have tried various messy ways like wrapping the whole code in window.onclick.
https://jsfiddle.net/esw6dbLn/1/
var total =0;
$('.box > .box_content > .box_price').each(function(){
total += parseInt($(this).text());
});
$('.container').append("<div class='sum'>Total : "+total+"</div>");
console.log(total);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<div class="container">
<div class="box">
<div class="box_content">
<div class="box_price">100</div>
</div>
</div>
<div class="box">
<div class="box_content">
<div class="box_price">200</div>
</div>
</div>
</div>
You can use click event on box_price div then get value of div which is been clicked and also the sum div value add them and display them inside your sum div.
Demo Code :
var total = 0;
$('.box > .box_content > .box_price').each(function() {
total += parseInt($(this).text());
});
$('.container').append("<div class='sum'>Total :<span> " + total + "</span></div>");
console.log(total);
$(".box_price").click(function() {
//get price which is clicked then add with sum
var price = parseInt($(this).text()) + parseInt($(".sum span").text().trim())
$(".sum span").text(price) //display in span
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box">
<div class="box_content">
<div class="box_price">100</div>
</div>
</div>
<div class="box">
<div class="box_content">
<div class="box_price">200</div>
</div>
</div>
</div>
You can put an empty div in your HTML and update it via an event listener that is added to each .box element, like:
// Finds all the boxes and calls `sumBoxes` whenever one is clicked
const boxes = document.getElementsByClassName("box");
for (let box of boxes){ box.addEventListener("click", sumBoxes); }
// Defines listener
function sumBoxes(event) {
var total = 0;
$('.box > .box_content > .box_price').each(function() {
total += parseInt($(this).text());
});
$('.sum').html("Total : " + total); // Replaces contents of `.sum`
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<div class="container">
<div class="box">
<div class="box_content">
<div class="box_price">100</div>
</div>
</div>
<div class="box">
<div class="box_content">
<div class="box_price">200</div>
</div>
</div>
<!-- Empty div to recieve sums -->
<div class="sum"></div>
</div>
You can listen for the .container click so anything inside the container will trigger the event and then do the calculation.
DEMO: https://jsbin.com/bokoman/edit?html,js,console,output
// Get the container
const container = document.querySelector('.container');
// Create an empty <span> and added to the end of the container
const totalEl = document.createElement('span');
container.appendChild(totalEl);
// listen for all the click but only do somethig if one of it childs was clicked
container.addEventListener('click', function(e) {
if (!e.target.classList.contains('container')) {
const prices = document.querySelectorAll('.box_price');
let total = 0;
prices.forEach(item => {
total += parseInt(item.innerText, 10)
})
// Add the total to the total element we created
totalEl.innerHTML = total
}
})
var total =0;
calculateResult = () =>{
total = 0;
$('.box > .box_content > .box_price').each(function(){
console.log()
total += parseInt($(this).text());
});
$('#sum').html("total:" + total);
}
$( "#target" ).click(function() {
$('.container').append("<div class='box'><div class='box_content'><div class='box_price'>100</div></div></div>");
calculateResult();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
</div>
<div id="result">
<div class='sum' id="sum">0</div>
</div>
<div id="target">
Add
</div>

How to sum a number in sequence after click a button?

$(document).ready(function(){
var current = 0;
current += 4;
$('.add').click(function(){
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>
i want to sum a number in sequence after click the add button like the above snippet, so the results will be 4 8 12 16 18 and so on. Teach me how to do this ?
Try this: Your increment should be in the click function as well. SO the increment actually occurs when you click, if it's outside, it won't occur.
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
You have to increment in click handler. Right now it is getting incremented only once.
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>
You need to move the line current += 4; to inside the click function . so only you can increment the value on click .otherwise you will get 4 for every click.
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>
Move count inside click function.
$(document).ready(function() {
var current = 0;
$('.add').click(function() {
current += 4;
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>
Try this:
The key is to grab the current value, add 4 to it and then replace that value with the new sum.
$(document).ready(function(){
$('.add').click(function(){
var existing = parseInt($("#result").text());
$('.box').text(existing + 4);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div id ="result" class="box">
0
</div>
Try this one. Get the box value and next check value is numeric if true then add 4 and bind value in div.
$('.add').click(function () {
var current = $('.box').text();
if ($.isNumeric(current))
$('.box').html(parseInt(current)+4);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div id ="result" class="box">
0
</div>
Move Current variable inside the click function..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
</script>
<button class="add">add</button>
<div class="box">
0
</div>
working example
It is very simple, you just need to use loop and a array variable. set limit according to your requirement.
<html>
<body>
<script type="text/javascript">
$(document).ready(function(){
var current = 0;
var c=0;
var res = [];
$('.add').on('click', function(){
for (c = 0; c < 3; c=c+1){
current += 4;
res[c] = current
$('.box').html('&nbsp'+res);
}
});
});
</script>
<button class="add">add</button>
<div class="box">
</div>
</body>
</html>

Input button stop working when filling the div

I have a div in my html defined like this:
<div id="rgroups" class="dialogWindow fileDialog" style="display:none;" >
<input id="rgroups_ok" class="dialogButton" type="submit" value="Done"/>
<label for="rgroups_ok"><span class="label">Start</span></label>';
</div>
In my js file the rgroups_ok is define that way:
$('rgroups_ok').observe('click', function ()
{
ui.hideDialog('rgroups');
});
If I keep to that it's working fine, the button is working.
Then I am filling that html div like that:
var div=document.getElementById('rgroups');
div.style.display='inline-block';
for (i = 1; i <= count; i++) {
div.innerHTML+=' Rgroup '+i+' values separated by / symbol: \n <textarea id="Rgroup"'+i+' rows="4" cols="50"> </textarea>';}
With that inner HTML defines button stops working...
Any clue?
Thanks
Try changing observe to on
so this:
$('#rgroups_ok').on('click', function ()
{
ui.hideDialog('rgroups');
});
You can check the details for on() here.
Observe seems to be obsolete and may not be a thing you are looking for.
I could not understand clearly. so I made demo code.
If you could mention your main subject/idea it would help us.
Full code:
Head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Body:
<div id="rgroups" class="dialogWindow fileDialog">
<label for="rgroups_ok">
<span class="label">Start</span>
</label>
</div>
<div id="rgroups2" style="display:none;">
<p onclick="textA()">Hey click here</p>
</div>
<button id="rgroups_ok2" class="dialogButton" onclick="a()">
Done
</button>
<script>
function a() {
$('#rgroups').css("display", "none");
$("#rgroups2").css("display", "inline-block");
$("#rgroups_ok2").css("display", "none");
};
function textA() {
var count = 100;
//document.getElementById("rgroups2").innerHTML += "Bye";
for (i = 1; i <= count; i++) {
document.getElementById("rgroups2").innerHTML += '<p> Rgroup ' + i + ' values separated by / symbol: \n <textarea id="Rgroup" rows="4" cols="50">' + i + ' </textarea></p>';
}
}
</script>
Hi found the solution on this post:
Is it possible to append to innerHTML without destroying descendants' event listeners?
To sum up it's not possible to append without destroying all child. Ths the event have to be reconstructed.
Thanks

JQuery DOM get Binded attribudes

I have a code
$(".showerPr").on('click', '.prototypeDiv',function(){
});
HTML looks like
<div class='showerPr' data-id='3'>
<div class='prototypeDiv' data-id='5'><div>
</div>
Is there some solution to get showerPr data-id and prototypeDiv data-id seperately?
somethink like
$(this).attr('data-id');
$(this).before().attr('data-id');
:-D thank you.
.showerPr isn't before() the .prototypeDiv element, it's the parent element
var proto = $(this).data('id');
var shower = $(this).parent().data('id');
$(".showerPr").on('click', '.prototypeDiv',function(){
var proto = $(this).data('id');
var shower = $(this).parent().data('id');
$('#result').html('prototypeDiv : ' + proto + '<br />' + 'showerPr : ' + shower)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='showerPr' data-id='3'>
<div class='prototypeDiv' data-id='5'>Click Me !!!<div>
</div>
<br/><br/>
<div id="result"></div>
#adeneo is right, .showerPr is the parent element. You may want to check the Traversing Methods for jQuery.
Here are the snippets.
$(".prototypeDiv").on('click', function(){
alert($(this).data('id'));
alert($(this).parent().data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='showerPr' data-id='3'>
<div class='prototypeDiv' data-id='5'>123<div>
</div>

Pass js var into html block being added via appendTo

I've got this html which i'm injecting into the page when someone clicks a button. The html gets appended again each time the button is clicked using the js below.
<div style="display: none;">
<div class="grab-me">
<p>This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
});
});
But what i need to do is where it says "This is fieldset 1" i need to increase that number by 1 each time so subsequent appends say This is fieldset 2, This is fieldset 3 etc etc. I can't see how i can pass a variable (my count var) in to the html block when it gets cloned that will replace that number.
Here is a jsfiddle of it: http://jsfiddle.net/tzbgA/
Any help would be great! Thanks!!
you can give the sentence you want to change class. Then using jQuery selectors change the text inside it.
<body>
<button class="add-member">add more</button>
<div style="display: none;">
<div class="grab-me">
<p class="count">This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
<div id="register">
</div>
</body>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register')
.find('p.count').html('This is fieldset '+count);
count += 1;
});
});
add span:
<p>This is fieldset <span>1</span></p>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
$('.span').html('count');
});
});
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me').clone();
$(grab p).html('This is fieldset '+count).appendTo('#register');
});
});
Fiddle: http://jsfiddle.net/howderek/tzbgA/2/
Here's a version that uses 8 lines of code:
Code (Javascript)
var count = 1,
html = ' <p>This is fieldset #</p><input name="foo[]"/> <input name = "bar[]"/> <input name = "oth[]"/>';
$(function () {
$('.add-member').live("click", function (e) {
e.preventDefault(e);
document.getElementById("register").innerHTML += html.replace("#",++count);
});
});

Categories

Resources