0

checkbox can not checked or uncheck by directly click on checkbox ?

i was create click on div for toggle checked/unchecked checkbox. this function was best.

But when i tried to click on checkbox directly, i can not check or uncheck checkbox.

How can i do that ?

https://jsfiddle.net/jddwxtst/

<script>
function onclick_cover_checkbox_fn(){
    var main_checkbox_checked_uncheck_var = document.getElementById("main_checkbox_checked_uncheck");
    var main_checkbox_checked_uncheck_var_checked_status = main_checkbox_checked_uncheck_var.checked;

    if(main_checkbox_checked_uncheck_var_checked_status != true)
    {
        document.getElementById("main_checkbox_checked_uncheck").checked = true;
        checked_all_or_uncheck_all_fn();
    }
    else
    {
        document.getElementById("main_checkbox_checked_uncheck").checked = false;
        checked_all_or_uncheck_all_fn();
    }
}
</script>

<script>
function checked_all_or_uncheck_all_fn(){
    alert("5555");
}
</script>
robert lovely
  • 55
  • 1
  • 6
  • even when you check it directly function `onclick_cover_checkbox_fn()` get executed and uncheck it. read this question and add it to `checked_all_or_uncheck_all_fn` function . http://stackoverflow.com/questions/1997084/prevent-parent-container-click-event-from-firing-when-hyperlink-clicked – Madhawa Priyashantha Mar 13 '16 at 02:19

2 Answers2

1

Here is a example in jquery:

Bind a change handler, then just uncheck all of the checkboxes, apart from the one checked:

$('input.example').on('change', function() {
    $('input.example').not(this).prop('checked', false);  
});

Here's a fiddle

0

here is the updated working example https://jsfiddle.net/jddwxtst/2/

problem is when you directly click on the checkbox it first run checked_all_or_uncheck_all_fn() method but then it execute onclick_cover_checkbox_fn() method too (you don't need) because div also receive click event.so if you check then method onclick_cover_checkbox_fn() method will uncheck it .to avoid this you shroud stop event propagating in checked_all_or_uncheck_all_fn() method.

function checked_all_or_uncheck_all_fn(e){
    alert("5555");
   // stop event propagating 

}

for cross browser stop propagating read this http://javascript.info/tutorial/bubbling-and-capturing

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60