September 18, 2012

Avoid displaying javascript confirmation when no checkbox is set

Question by peter burg

Like the title says, I have a problem with checkbox validation.
So, I have this line in my php file which displays users.

<a href='#' onclick='if(confirm("Are you sure?"))checkbox.submit()' class='bt_red'><span class='bt_red_lft'></span><strong>Delete items</strong><span class='bt_red_r'></span></a>

in my delete_items.php file I wrote the following :

$checkbox = $_REQUEST['checkbox'];
if(!isset($checkbox)) {
//diplay an error message :"No user selected"
} else {
if(isset($checkbox)) {
// deleting users script
}
}

In the 2 cases, when clicking on the “delete items” , I get the javascript confirmation message, which I don’t want to display when no checkbox is set (the if(!isset($checkbox)) statement).

thank you for help.

Answer by sra

You would want to make the javascript code inside your links onclick statement aware of how many checkboxes have been clicked. This is rather easy. If you use Jquery you can just query them like this:

$("input[type=checkbox]:checked").size();

This just evaluates to how many checkboxes are checked anywhere on your page, so you would have to narrow down the query with a parent element or class or something.

When you have the number of checked checkboxes, its just a matter of some AND and OR like this:

$("input[type=checkbox]:checked").size() > 0 && (confirm("do you really want to do this?"));

The first expression evaluates to true if there are checked checkboxes, so the second expression gets evaluated, otherwise not.

hope this helps

edit: you could also use if instead of or. maybe that’s a little bit more familiar

Answer by Starx

First, there is lot of ambiguous lines in your code. Same thing can be done like this

if(!isset($_REQUEST['checkbox'])) {
  //diplay an error message :"No user selected"
} else  {
  //delete user's script
}

If you dont want the confirm message if no checkbox is set, then you can do this:

<?php if(isset($_REQUEST['checkbox'])) {
        echo '<a href="#" onclick="if(confirm("Are you sure?"))checkbox.submit()" class="bt_red">';
     } else {
        echo '<a href="#" class="bt_red">';
     }
?>
    <span class='bt_red_lft'></span>
    <strong>Delete items</strong>
    <span class='bt_red_r'></span>
</a>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!