Obligate to fill input in php

0

I created a table with 2 input type radio , where one receives the value="Ok" and the other the value="Não Ok" and immediately ahead a column of observation.

$tabela1 .= '<td style="float:center"> <input type="radio" name= "Sim['.$y.']" value="Ok" required></td>';
$tabela1 .= '<td style="float:center"> <input type="radio" name= "Sim['.$y.']" value="Não Ok" required></td>';
$tabela1 .= '<td> <textarea type="text" class= "Observacao" name="Observacao['.$y.']" rows="2" cols="30"></textarea></td>';

The inputs type radio are required. Now I always wanted the input type radio to receive the value="Não Ok" , to compile the input of the observation, but only to oblige in that situation.

    
asked by anonymous 10.12.2018 / 14:05

3 answers

1

You can do this using JavaScript (with JQuery) by changing the value of the required attribute of textarea.

In PHP you have to put a class in td of textarea (It would do without, but it gets better using a class if you put another td between these two in the future).

<?php
    $tabela1 .= '<td style="float:center"> <input type="radio" name= "Sim['.$y.']" value="Ok" required></td>';
    $tabela1 .= '<td style="float:center"> <input type="radio" name= "Sim['.$y.']" value="Não Ok" required></td>';
    $tabela1 .= '<td class="obs"> <textarea type="text" class= "Observacao" name="Observacao['.$y.']" rows="2" cols="30"></textarea></td>';
?>

In JavaScript just take the click of the input and check its value, changing the textarea as necessary:

<script type="text/javascript">
    $('input[type=radio]').click(function(){
        if($(this).val() == "Não Ok"){
            $(this).parent().siblings('td.obs').children('textarea').attr('required', 'true');
        }else{
            $(this).parent().siblings('td.obs').children('textarea').removeAttr("required");
        }
    });
</script>
    
10.12.2018 / 14:21
1

The method of validating the form via the Back-End is more efficient than the Front-End, although it is ideal to use both methods.

    
10.12.2018 / 17:24
0

I think a simple PHP solution would look something like this:

<input type="radio" name="opcao" value="Ok">
<input type="radio" name="opcao" value="Não Ok">
<textarea type="text" name="observacao"></textarea>

if(empty($_POST['opcao']) && empty($_POST['observacao'])){

    echo "<script>alert('Escolha uma opção ou preencha a Observação.');</script>";

}elseif(!empty($_POST['opcao']) || !empty($_POST['observacao'])){

    echo "<script>alert('Ok!');</script>";
}
    
10.12.2018 / 14:59