user3724238
user3724238

Reputation: 3

Alert if dynamic checkbox is checked/unchecked

Hi I have a dynamic checkboxes that are ticked if the user wants to delete a certain row. Now what I want is an alert that will say "Are you sure you want to delete?" if any one of the checkboxes are checked and "Nothing selected!" if non of the checkboxes are selected. This is what I have so far:

HTML:

<th><input type="checkbox" name="select[]" value="<?php echo $row_direct['id']; ?>"></input></th>

Script:

<script language="JavaScript" type="text/javascript">
var $delete = jQuery.noConflict();

$delete(document).ready(function(){

    $delete(".delete").click(function(e){

        if (document.getElementsByName('select[]').checked == false){
            alert('nothing is checked');
            e.preventDefault();
            return false;
        }

        else {
        if(!confirm('Are you sure you want to delete?')){
            e.preventDefault();
            return false;
        }
        return true;
        }

    });
});
</script>

What's happening is that I only get the "Are you sure you want to delete?" alert no matter if a checkbox is checked or not.

Any help would be greatly appreciated. Thanks!

Upvotes: 0

Views: 681

Answers (2)

NullPointer
NullPointer

Reputation: 442

The .checked on the getElementsByName function does not work because getElementsByName returns an array of elements. This should work:

if (document.getElementsByName('select[]')[0].checked == false){ ...

However, since you have jQuery loaded Aguardientico has a nicer solution for you.

Upvotes: 0

Aguardientico
Aguardientico

Reputation: 7779

if ($delete('[name="select[]"]:checked').length > 0) {
  alert('Are you sure?');
} else {
  alert('Nothing checked');
}

Upvotes: 1

Related Questions