how to avoid sending empty fields in html with php

0
<table>
                <tr>
                    <th>Nombre</th>
                    <td><input type="text" name="nombre"/></td>
                </tr>
                <tr>
                    <th>Apellido</th>
                    <td><input type="text" name="apellido"/></td>
                </tr>
                <tr>
                    <th>Cedula</th>
                    <td><input type="text" name="cedula"/></td>
                </tr>
                <tr>
                    <th>Sexo</th>
                    <td><input type="text" name="sexo"/></td>
                </tr>
</table>
<button type="submit" onclick ="guardarDatos();">Guardar</button>

I have the code that is supposed to work like this:

var DATOS = [];
function guardarDatos(){
    inps= document.getElementsByTagName('input');

    for(k in inps){
        if(inps[k].value==''){
            alert("Debe Completar "+inps[k].id);
            return false;
        }
    }   
}

But it does not do anything.

    
asked by Samuel Ignacio Susana Confesor 29.06.2017 в 19:44
source

1 answer

1

Hi, you could add the following HTML5 code to the input:

  Username: <input type="text" name="usrname" required>

and now, your field validation problem will be solved natively by HTML5 without javascript.

Source

but if your purpose is to validate with Javascript here you have an example explained line by line:

<!DOCTYPE html>
<html>
<head>
<script>
//creamos un pequeña funcion la cual sera llamada desde el html
function validateForm() {
//capturamos el valor(value) de myfrom/fname 
    var x = document.forms["myForm"]["fname"].value;
  //validamos para ver si existe un valor agregado al input
    if (x == "") {

// y si no fue agregado ninguna informacion que te mande un alert notificando que es obligatorio.
        alert("Name must be filled out");
        return false;
    }
}
</script>
</head>
<body>



<form name="myForm" action="/action_page_post.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

and a tip of mine, if you are using a form to save data or something similar avoid the table, why? Because you should not use tables for forms or Div, only to order information brought from the BD.

    
answered by 29.06.2017 / 20:19
source