samedi 8 juillet 2017

Add the same event handler to radio buttons and checkboxes

I am trying to have a function add the values of selected check boxes and radio buttons. I have created a function that can add the values of the check boxes and a function for the radio buttons but am having trouble combining the two into one working function. I think my issue is with having both radio and checkbox elements associated with the .click()

My code can be seen here: http://ift.tt/2tuMWZp

The HTML is:

<input type="checkbox" value="1" />test 1<br/>
<input type="checkbox" value="2" />test 2<br/>
<input type="checkbox" value="3" />test 3<br/>

<input type="radio" name="test" value="1" />test 4
<input type="radio" name="test" value="2" />test 5
<div id='sum'></div>

The jQuery is:

jQuery(document).ready(function($) {
var sum = 0;

$("input:checkbox"),$("input:radio").click(function() {
   sum = 0;
    $("input:checkbox:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });

   sum = 0;
    $("input:radio:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });
    $('#sum').html(sum);
  });
});




Aucun commentaire:

Enregistrer un commentaire