Force to fill in php input

Asked

Viewed 251 times

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 just ahead an observation column.

$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 mandatory. Now always intended that the input type radio received the value="Não Ok", required the completion of the input of the observation, but only oblige in that situation.

3 answers

1


You can do this using Javascript (with Jquery), by changing the value of the required attribute of textarea.

In PHP you need to put a class in td textarea (You could do without, but it is 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 needed:

<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>
  • thus obliging to fill in the input observacao both fill the radio Ok or Não Ok

  • 1

    Dude, you can check the browser console for javascript and put a breakpoint to check the field value ($(this).val()) is coming correctly and if he is entering the if right. In case it’s all right change .attr('required', 'false') for .removeAttr( "required" ) in Else.

1

The form validation method via the Back-End is more efficient than the Front-End, although ideally the two methods are used.

0

I believe that a simple solution in PHP would be 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>";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.