Sum between Divs and display result in another div

Asked

Viewed 260 times

0

I don’t understand why I can’t run the following script because I’m a bit of a layman:

    <div class="prices"> 
<h3>Option 1 = $<span class="sum" id="option-1">11.11</span></h3>
<h3>Option 2 = $<span class="sum" id="option-2">22.22</span></h3>
</div>
<div id="subtotal"></div>

and the script...

$(document).ready( function() {

    $('#option-1, #option-2').blur(function(){
        var sum = $('#option-1').text();
        var sum2 = $('#option-2').text();

        if(sum == "") sum = 0;
        if(sum2 == "") sum2 = 0;

        var resultado   = parseInt(sum) + parseInt(sum2);
  $("#subtotal").text(resultado);
    })

});

Or if you have some simpler way to do this function but need to specify each div.

2 answers

0

Hello,

well, the . Blur is a function that is expected to lose focus, tags as span has no focus, just make a .hover instead of .blur that you can see perfectly well that your code works. I will post here the proof of what I’m talking about, just take the focus of some input that your result appears.

 <div class="prices"> 
    <h3>Option 1 = $<input type='text' class="sum" id="option-1"n value='11.11'/></h3>
    <h3>Option 2 = $<input type='text' class="sum" id="option-2" value='22.22' /></h3>
</div>
<div id="subtotal"></div>

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
(function() {
    $('#option-1, #option-2').blur(function(){
        var sum = $('#option-1').val();
        var sum2 = $('#option-2').val();

        if(sum == "") sum = 0;
        if(sum2 == "") sum2 = 0;

        var resultado   = parseInt(sum) + parseInt(sum2);
        $("#subtotal").text(resultado);
    })

})();
</script>

0


The desired result (when you click anywhere) can be obtained with

$(document).click(function() {

because with

$('#option-1, #option-2').blur(function(){

said by Vinicius.Beloni "o. Blur is a function expected to lose focus, tags like span have no focus"

$(document).ready( function() {

    $(document).click(function() {
    
        var sum = $('#option-1').text();
        var sum2 = $('#option-2').text();

        if(sum == "") sum = 0;
        if(sum2 == "") sum2 = 0;

        var resultado   = parseInt(sum) + parseInt(sum2);

        $("#subtotal").text(resultado);

    })

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="prices"> 
<h3>Option 1 = $<span class="sum1" id="option-1">11.11</span></h3>
<h3>Option 2 = $<span class="sum2" id="option-2">22.22</span></h3>
</div>
<div id="subtotal"></div>

  • That’s right, with the .click resolves very well the question of the colleague, thanks for the quote :D

  • Worked perfectly and enhanced with attr. to facilitate... Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.