Mark radiobutton in php

Asked

Viewed 782 times

-1

How do I leave the radiobutton "checked" in PHP ? I’m having trouble with that the name of the radiobutton is sex and I need to do a check in the database if the sex is’M' it marks one of the sex radiobutton otherwise it marks the other sex radiobutton. I’ve done SELECT and it returned the value of the other variables normally, I just want to know how to mark a radiobutton, my code is wrong ? I have checked if the variable is receiving the sex value correctly and is, the condition code is after the creation of the radiobutton, I can not think of anything that is wrong, can only be the way I am marking the radiobutton.

 <label>Sexo:</label><input type="radio" name="sexo" value="M"/>
 <label>Masculino</label>

 <input type="radio" name="sexo" value="F"/>
 <label>Feminino</label>

 if($vsexo == 'M')
 {
  echo "<script type='text/javascript'>sexo[0].checked = true;</script>";
 }
 else
 {
  echo "<script type='text/javascript'>sexo[1].checked = true;</script>";
 }
  • what is "trust"?

  • Checked ? dial the radiobutton

  • Ah... condition... When loading the document you want it to be marked according to the information received from the database, right?

  • That’s right .!.

  • You know what to do to score ?

2 answers

0


Test like this:

<label><input value="M" type="radio" name="sexo" <?= $vsexo == 'M' ? 'checked="true"' : ''; ?>>Masculino</label>
<label><input value="F" type="radio" name="sexo" <?= $vsexo == 'F' ? 'checked="true"' : ''; ?>>Feminino</label>
  • Didn’t work out..

  • Unlikely :D. What is happening?

  • Worked out now, thanks boss !

  • I don’t know why your code didn’t work, but I made one that looked like yours and it worked:

  • <?php if($vsexo == ’M'){echo "checked";}?>

  • That within the input

  • I had written your code wrong, now that I saw the = without the php tag, I didn’t understand why

  • For information purposes: <?= $vsexo == 'M' ? 'checked="true"' : ''; ?> is exactly the same thing as <?php if($vsexo == 'M'){echo "checked";} ?>. It’s called ternary operator read more here.

  • I realized, so much so that I did with what I know best, I saw exactly the idea of this code of yours, but I missed the beginning of it, I had not noticed that there is no php

Show 4 more comments

-2

$sexo = mysql_fetch_array(mysql_query("SELECT campo_sexo FROM tabeladedados"));
$sexo = ($sexo[0] || "M");
<?php
    if(strtolower($Sexo) == "M"):
?>
    <input type="radio" name="sexo" value="M" checked="checked" />
<?php
    else:
?>
    <input type="radio" name="sexo" value="M" />
<?php
    endif;
?>
  • There are already the radiobutton, there you are creating another, I want to check the value of the variable sex and according to the value mark one of the existing radios

Browser other questions tagged

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