Misuse of confirm () with PHP and Javascript

0

I have a table with sorted data in rows and columns. A column is for delete , with checkboxs selected, when we press the DELETE button and a " confirm () "to confirm the deletion or be canceled.

In the second question I have the problem: in the cancellation. If I cancel, the checkboxs are not erased or deactivated ... I can not get it!

HTML / PHP code:

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Panel del administrador</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script type="text/javascript" src="js/desmarcar_checkboxs.js"></script>
    </head>

    <body>
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="tabla_datos_cabana" id="tabla_datos_cabana" method="POST">
            <div id="mostrar_cabanas">
                <table class="table table-striped" id="tabla" name="tabla" width="600" border="2" cellspacing="3" cellpadding="3" style="font-size: 10pt">
                    <center>
                        <tr>
                            <thead style="background-color:#A9F5A9">
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>Eliminar</center></b></font>
                                </td>
                            </thead>
                        </tr>
                        <?php
                        $datos = BD::obtenerCabanas();
                        foreach($datos as $cabana){
                            echo "<tr>";
                               echo "<td width=\"150\"><center><input type='checkbox' name='marcados[]' id='marcados[]' value=".$cabana->getIdcabana()."></center>";
                            echo "</tr>";
                        }
                        ?>
                    </center>
                </table>


                <!-- Botón ELIMINAR cabaña/s -->
                <div class="boton_eliminar" class="table-responsive" align="left">
                    <font face="verdana">
                        <b><input type="submit" style="width:200px; height:28px;" name="eliminar_cabanas" id="eliminar_cabanas" onclick="return confirm('¿Deseas realmente eliminar estas cabañas?');" value="Eliminar cabañas" /></b>
                    </font>
                </div>

                <?php
                //Si pulsamos el botón "Eliminar cabañas"...
                if(isset($_POST['eliminar_cabanas'])){
                    if(empty($_POST['marcados'])){
                        echo "<h4><center>No se ha seleccionado ninguna cabaña.</center></h4>";
                    }else{
                        foreach($_POST['marcados'] as $valor){
                            //Nos conectamos a la base de datos.
                            $conexion = mysqli_connect("localhost", "root", "root", "osmarrural");
                            //Realizamos la consulta.
                            $sql = sprintf("DELETE FROM cabanas WHERE idcabana='%d'", $valor);
                            $resultado = mysqli_query($conexion, $sql);
                        }
                        echo "<meta http-equiv=\"refresh\" content=\"0; URL=menu_administrador.php\">";
                    }
                }
                ?>
            </div>
        </form>
    </body>
</html>

File call code uncheck_checkboxs.js:

//Seleccionamos el botón.
var btn = document.getElementById('eliminar_cabanas');
//Asignamos el evento click.
btn.onclick = function(e){
    //Obtenemos y asignamos el valor de retorno de confirm: true o false.
    let option =confirm('¿Deseas realmente eliminar estas cabañas?');
    if(!option){ //Si es falso...
        //Seleccionamos todos los checks.
        let checks = document.querySelectorAll('input[type="checkbox"]');
        //Iteramos sobre estos.
        checks.forEach(function(el){
            //Asigamos el atributo a false.
            el.checked = false; 
        });
    }
}

If I get the inspector with F12, I get the following error:

Uncaught TypeError: Cannot set property 'onclick' of null
    at desmarcar_checkboxs.js:5

Error image:

    
asked by omaza1990 06.01.2018 в 19:59
source

1 answer

1

I see some problems like that:

Define the onclick directly in the HTML and then in the code

You do not close the td elements when creating the checks

All checks have the same ids and these include brackets.

You do not cancel the sending of the form in case the user cancels the operation. In this case, the function should return false to cancel the execution.

The error it gives you indicates that the getElementById method has not returned any results and therefore btn is null . This is because, as you comment, you have your code js in the head of the page.

The browser executes the javascript code of the page while it is interpreting the HTML code. That is, if the code is before the body will be executed before the elements of the page are created, if the code is at the end (after body the elements will already be created). Obviously if the code is in the middle of the page, apart from being more confusing, at the time of execution there will be some elements (those defined before the code) and others will not.

The easiest solution is, as I said, to put the code at the bottom of the page. Another option would be to put the code in a function and associate it with the event DOMContentLoaded of the object document .

//Seleccionamos el botón.
var btn = document.getElementById('eliminar_cabanas');
//Asignamos el evento click.
btn.onclick = function(e){
    //Obtenemos y asignamos el valor de retorno de confirm: true o false.
    let option =confirm('¿Deseas realmente eliminar estas cabañas?');
    if(!option){ //Si es falso...
        //Seleccionamos todos los checks.
        let checks = document.querySelectorAll('input[type="checkbox"]');
        //Iteramos sobre estos.
        checks.forEach(function(el){
            //Asigamos el atributo a false.
            el.checked = false; 
        });
    }
    return option;
}
<form action="" name="tabla_datos_cabana" id="tabla_datos_cabana" method="POST">
    <div id="mostrar_cabanas">
        <table class="table table-striped" id="tabla" name="tabla" width="600" border="2" cellspacing="3" cellpadding="3" style="font-size: 10pt">
            <center>
                <tr>
                    <thead style="background-color:#A9F5A9">
                        <td width="150">
                            <font face="verdana" color="blue"><b><center>Eliminar</center></b></font>
                        </td>
                    </thead>
                </tr>
                <tr>
                  <td width="150"><center><input type='checkbox' name='marcados[]' id='marcados[]' value="cab1"></center></td>
                </tr>
                <tr>
                  <td width="150"><center><input type='checkbox' name='marcados[]' id='marcados[]' value="cab2"></center></td>
                </tr>
                <tr>
                  <td width="150"><center><input type='checkbox' name='marcados[]' id='marcados[]' value="cab3"></center></td>
                </tr>
                <tr>
                  <td width="150"><center><input type='checkbox' name='marcados[]' id='marcados[]' value="cab4"></center></td>
                </tr>
            </center>
        </table>

        <!-- Botón ELIMINAR cabaña/s -->
        <div class="boton_eliminar" class="table-responsive" align="left">
            <font face="verdana">
                <b><input type="submit" style="width:200px; height:28px;" name="eliminar_cabanas" id="eliminar_cabanas" value="Eliminar cabañas" /></b>
            </font>
        </div>
    </div>
</form>
    
answered by 06.01.2018 / 20:40
source