K
K
Kyrat Farre2015-10-13 19:20:28
JavaScript
Kyrat Farre, 2015-10-13 19:20:28

How to display the total sum of all values ​​in a document?

there is a code:

function calc() {
            
            var select1 = document.getElementById("select1");
            var select2 = document.getElementById("select2");
            var select3 = document.getElementById("select3");
             var select4 = document.getElementById("select4");
             var select5 = document.getElementById("select5");
              var select6 = document.getElementById("select6");
             

           
            var result = document.getElementById("result");
 
            var price = 100;
            price = parseInt(select1.options[select1.selectedIndex].title) +
            parseInt(select2.options[select2.selectedIndex].title) +
             parseInt(select3.options[select3.selectedIndex].title) +
             parseInt(select4.options[select4.selectedIndex].title) +
             parseInt(select5.options[select5.selectedIndex].title) +
              parseInt(select6.options[select6.selectedIndex].title);
         
            result.innerHTML = price;
       }


But this code counts and shows only those values ​​​​that I chose, that is, the function returns the value to me BUT DOES NOT SUM IT ((, please tell me how to write, so that when choosing some value, the sum is calculated, and not selected, thanks)))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Martirosov, 2015-10-13
@kalbac

Is it necessary to do it with native javascript, or is jQuery suitable?)

( function( $ ) {
  
  $('select').each(function(){
    var _select = $(this);
    var value = 0;

    _select.on('change', function(){
      var _this = $(this);
      value += parseInt( _this.val() );
    }).change();
    
    var result = $('<span />',{
      'class': 'amount',
      'text': value
    });
    $('#result').empty().html( result );	
  });
  
})( window.jQuery );

The code was written on the knee, just not tested. For example only.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question