validate that at least one checkbox is cheked

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 so far the form but it is sent even though I have not selected any material when I have not clicked on my check.

To validate a checkbox I need the name property, but the detail and my problem is that in the name I have a variable that fills my table and in turn that variable I use to send it to another page

name = ''

and I do not know how to change that.

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 11.12.2018 в 20:28
source

1 answer

0

We are going by part progressing in the answer.

1 - for readability, it would make a change in the route of the result of your query to use the names of the fields instead of using the index of the field in the query. We change mysql_fetch_array by mysql_fetch_object and it looks like this:

<?
    while ($mat=mysql_fetch_object($m_result)) {
?>
        <tr>
            <td><?=$mat->material?></td>
            <td><input type='checkbox' name='mat<?=$mat->id?>'/></td>
          </tr>
<?
    }
?>

2- To know if a checkbox is "checked" we use a selector with jQuery, with this we know how many checkboxes have been selected by the user, if this results in cero then we do not send the form.

$('input[type=checkbox]:checked').length


function valida(){    
 if ($('input[type=checkbox]:checked').length==0){       
    alert("Indique el material de la cotización o pedido.");
    return false;
 }
}

If something else is missing, or I did not fully understand what you needed, tell me to correct and help you.

    
answered by 11.12.2018 / 21:06
source