as valid checkbox

0

I have a table with a list of materials and a check to the side are part of a form, what I want to do is not send my form until all the fields are filled with my check, because until the moment I fill in the form but it is sent even though I have not selected any material when I did not click on my check

function valida(document)
{    
 if (document.check.value =="")
    {       
        alert("Indique el material de la cotización o pedido.");
        document.check.focus();
    return false;  }
}

<?php
$m=mysql_query("select id, material from material");
?>
<?php
if (!isset($_GET['id'])) {
?>
<table class='mat' border='1'>
<tr><td>MATERIAL</td><td>Seleccione</td></tr>
<?php
while ($m1=mysql_fetch_array($m)) {
?>
<tr><td><?php echo $m1[1];?></td><td><input type='checkbox' name='<?php echo "mat".$m1[0]?>' id='check' value=''/></td></tr>
<?php 
}
?>
</table>
    
asked by jasiel torres 10.12.2018 в 21:11
source

2 answers

0

What you could do is a form and call a function of js to validate that all the fields have been filled in.

<form name="formulario" action="" onsubmit="return validate()" method="POST">
    <input type="text" name="name" id="name">
    <input id="checkbox" name="checkbox" type="checkbox">
<form />

And the function in js:

function validate() {
    name = document.getElementById('name').value;
    checkbox = document.getElementById('checkbox');

    if (name == null || name.length == 0) {
        console.log('Error');
        return false;
    }
    else if( !checkbox.checked ) {
        console.log('Error');
        return false;
    }
    return true;
}

If the validation happens, the data will be sent to where the form says, if they do not pass, it will show an error on the screen.

One of the best practices is that the validations are carried out by the server when receiving data, because the user can deactivate the JS or modify it on the client's side, but I hope it serves you.

It's just an example, greetings!

    
answered by 10.12.2018 в 23:42
0

To validate all the checkboxes in the javascript code you must search by the name, not by the id (which should be different by the regras of the HTML). The name of the list of checkboxes should be the same for all fields of the material:

<table class='mat' border='1'>
<tr><td>MATERIAL</td><td>Seleccione</td></tr>
<?php
while ($m1=mysql_fetch_array($m)) {
?>
<tr><td><?php echo $m1[1];?></td><td><input type='checkbox' name='material' id='<?php echo "mat".$m1[0]?>' /></td></tr>
<?php 
}
?>
</table>

The function to validate would be:

function validate() {
    var values = document.getElementsByName("material");
    for(var i=0; i < values.length; i++){
    	var checked = values[i].checked;
        if(!checked) {
        	alert("Error"); return false;
        }
    }
    return true;
}
    
answered by 11.12.2018 в 00:02