Search code examples
javascriptsummultiplication

How to Multiply / Sum with Javascript


https://jsbin.com/wujusajowa/1/edit?html,js,output

I can sum the numbers of options. Like (5+5+5=15)

But I don't know a way to multiply the input with the sum of selects.

For example, What should I do to do 6 x (5+5+5) and get 90 ?


Solution

  • Use <input type="number">, define a global variable to store value of <input>; attach change event to <input> element to update global variable; use variable at change event of <select> element if variable is defined, else use 1 as multiplier

    var input = 0;
    
    $('select').change(function(){
     var sum = 0;
        $('select :selected').each(function() {
            sum += Number($(this).val());
        });
         $("#toplam").html(sum * (input || 1));
    }).change();
    
    $("#miktar").on("change", function() {
      input = this.valueAsNumber;
    });
    

    jsbin https://jsbin.com/cujohisahi/1/edit?html,js,output