Search code examples
javascriptformscss-selectorsselectors-api

Pass values from checkboxes using Javascript


Im building a simple form where im trying to pass values from check boxes...

<div class="checkboxclass">
<input name="form[paperdesign][]" value="150" id="paperdesign0" type="checkbox">
<label for="paperdesign0">text 1</label>
<input name="form[paperdesign][]" value="100" id="paperdesign1" type="checkbox">
<label for="paperdesign1">text 2</label>
<input name="form[paperdesign][]" value="50" id="paperdesign2" type="checkbox">
<label for="paperdesign2">text 3</label>
<input name="form[paperdesign][]" value="50" id="paperdesign3" type="checkbox">
<label for="paperdesign3">text 4</label>
</div>

...using this function:

function calculate(){
    var sela=document.querySelectorAll("div.checkboxclass input");
    resultsel.value=0;
    resultsel.value=parseInt(resultsel.value);
    for(i=0;i<sela.length;i++)
        resultsel.value=parseInt(resultsel.value)+parseInt(sela[i].value);
}

And it works OK apart from the fact that it's passing this all the values at this same time.

Could comeone please help me out on this one?

many Thanks in advance

Dom


Solution

  • If I understand the question, you mean that you only want to include the values for the checked items. In this case, you should be able to use the :checked selector:

    var sela=document.querySelectorAll("div.checkboxclass input:checked");