Sum between DIVs and display result in another div

0

I do not understand why I can not execute the following script because I am somewhat of a layperson:

    <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 would have some simpler way to do this function however I need to specify each div.

    
asked by anonymous 07.08.2017 / 06:29

2 answers

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 ".blur is a function that is expected to lose focus, tags like span has 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><divclass="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>
    
07.08.2017 / 13:48
0

Hello,

Well, the .blur is a function that is expected to lose focus, tags like span does not have focus, just make a .hover instead of .blur that you see perfectly that your code works . I'll post here the proof of what I'm talking about, just get 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(){varsum=$('#option-1').val();varsum2=$('#option-2').val();if(sum=="") sum = 0;
        if(sum2 == "") sum2 = 0;

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

})();
</script>
    
07.08.2017 / 08:30