salah tabet
salah tabet

Reputation: 119

JavaScript alert on click event if no checkboxes are checked

Every thing works normally except when I check all the rows and try to delete them with a button.

I put an alert in the delete button which tests if any rows are checked, so when I click the button and no boxes are checked, it shows the alert.

Also when all the boxes are checked how do I change it or where do I put it? I am new to JavaScript and php.

Or can I change it to a delete confirmation alert!

Here is my code .

<script>

function checkUncheckAll(){
var chks = document.getElementsByName("ck");
if(document.getElementById("ck_All").checked)
    {
        $("#delete_link").on("click" , deleteSelectedRows);
        for( i = 0;i < chks.length;i++)
            document.getElementsByName("ck")[i].checked = true;
    }
else {
            for( i = 0;i < chks.length;i++)
            document.getElementsByName("ck")[i].checked = false;
            document.getElementById("delete_link").onclick = function(){deleteSelectedRows();};
    }
}
function selectUnselect(checked){
if(!checked)
    document.getElementById("ck_All").checked = false;
else {
        document.getElementById("delete_link").onclick = function(){deleteSelectedRows();};
        var chks = $("input[name='ck']");
        var all_checked = true;
        for(i=0;i<chks.length;i++)
            if(chks[i].checked)
                continue;
            else {all_checked = false; break;}
        if(all_checked)
            document.getElementById("ck_All").checked = true;
     }
}
function deleteSelectedRows(){
    var cks = $("input[name='ck']");
    var checked = [];
    for(i = 0;i<cks.length;i++)
        if(cks[i].checked)
            checked.push(cks[i].parentNode.parentNode.id);

    var jsonob = JSON.stringify(checked);
    $.post("deletecom.php" , {rows_to_be_deleted:jsonob} , function(data){
        for(i=0;i<checked.length;i++)
            $("#" + checked[i]).fadeOut('slow' , function(){$(this).remove();});
        });
    }
    </script>


<a id="delete_link" onclick="alert('Aucune case n est cochée')">Supprimer</a>
<br><br>

<?php
    $con = new mysqli('localhost' , 'root' , 'etud' , 'responses');

    echo "<div id='divtable'>";
    echo '<table class="table" >';
    echo '<tr id="throws"> 
        <th><input id="ck_All" type="checkbox" onchange="checkUncheckAll()" />Select</th>
        <th>Nom</th>
         <th>Email</th>
         <th>Sujet</th>
         <th>Messages</th>
          <th>Date Creation</th>';

 // if (isset($_POST['date'])& isset($_POST['btncherche'])) {
    error_reporting(E_PARSE);
    $datechoosen=$_POST['date'];
    $result = $con->query("select * from tb_cform where datecreation='".$datechoosen."'");   
    while($row = $result->fetch_assoc())
        echo '<tr id="' . $row['id'] . '">
            <td><input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" /></td>
            <td>' . $row["u_name"] .'</td>
            <td> '. $row["u_email"] . '</td>' .  
            '<td>' . $row["subj"] . '</td>' .
            '<td>' . $row["message"] . '</td>' .
            '<td>' . $row["datecreation"] . '</td>' .
            '</tr>';

    echo '</table>';
    echo "</div>";

/*  }else{
        echo "veuillez choisir la date S.V.P !";

    }*/
 ?>

When I click the delete button the alert keeps showing no matter what the condition is, help me please! enter image description here

Upvotes: 0

Views: 691

Answers (1)

Seb Cooper
Seb Cooper

Reputation: 574

One thing I must point out is that it is best to keep your click event handlers out of your HTML and bundled with the rest of your JavaScript, see Why is using onClick() in HTML a bad practice?.

Please see my working example on JSFiddle: https://jsfiddle.net/fL91x2am/23/

Working code:

<script>
    function deleteSelectedRows(){
    var cks = $("input[name='ck']");
    console.log(cks.length);
    var checked = [];
    // Add ids of checked messages to checked array
    for(i = 0;i<cks.length;i++){
        if(cks[i].checked){
            checked.push(cks[i].parentNode.parentNode.id);
        }
    }

        // AJAX delete POST
    var jsonob = JSON.stringify(checked);
    $.post("deletecom.php" , {rows_to_be_deleted:jsonob} , function(data){
        for(i=0;i<checked.length;i++){
            // hide deleted messages row if delete POST successful
            $("#" + checked[i]).fadeOut('slow' , function(){
                $(this).remove();
            });
        }
    });
}

function checkUncheckAll(){
  // var chks = all checkboxes
  var chks = document.getElementsByName("ck");

  // if select all checkbox is checked
  if(document.getElementById("ck_All").checked) {

    for( i = 0;i < chks.length;i++ ){
      document.getElementsByName("ck")[i].checked = true;
    }

  } else {

        for(i = 0;i < chks.length;i++){
      document.getElementsByName("ck")[i].checked = false;
        }
    }
};

function selectUnselect(checked){
    if(!checked){
    document.getElementById("ck_All").checked = false;
    } else {
        document.getElementById("delete_link").onclick = function(){
            deleteSelectedRows();
        };
        var chks = $("input[name='ck']");
        var all_checked = true;
        for(i=0;i<chks.length;i++){
            if(chks[i].checked){
                continue;
            } else {
                all_checked = false; 
              break;
            }
        }
        if(all_checked){
            document.getElementById("ck_All").checked = true;
        }
    }
}
// Here we use jQuery's document ready event listener to add the click event listener to #delete_link.  
$(document).ready(function(){
  $('#delete_link').on('click', function(){
    // (jQuery syntax) - check if number of checked inputs with name attribute of 'ck' is zero
    if($('input[name="ck"]:checked').length === 0){
      alert('Please select an item!');
    } else {
    // or confirm if the user really wants to delete
      var warning = confirm("Are you sure you want to delete?");
      if (warning == true) {
         deleteSelectedRows();
      } 
    }
  });
})

</script>
<a id="delete_link">Supprimer</a>
<br><br>
<div id="divtable"><table class="table">
    <tr id="throws"> 
        <tr><th><input id="ck_All" type="checkbox" onchange="checkUncheckAll()" />Select</th>
        <th>Nom</th>
         <th>Email</th>
         <th>Subject</th>
         <th>Messages</th>
          <th>Date Creation</th></tr>
          <tr id="1">
            <td><input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" /></td>
            <td>Name</td>
            <td>Email</td>' .  
            <td>Subject</td>
            <td>Lorem ipsum dolor</td>
            <td>2017-01-01</td>
    </tr>
    <tr id="2">
            <td><input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" /></td>
            <td>Name</td>
            <td>Email</td>' .  
            <td>Subject</td>
            <td>Lorem ipsum dolor</td>
            <td>2017-01-01</td>
    </tr>
  </table>
</div>

Upvotes: 1

Related Questions