简体   繁体   中英

Using PHP to set checked option on a radio button based on data from database. BUT it only works on some data

Here is the code snippet, which is inside a form:

<fieldset>

<!-- for each radio button, PHP code used to check IF $id==value 
     to determine what should be checked. -->
<div class="newrow">
    <label>Status:</label>
    <div class="radio-group">
        <input type="radio" id="active" value="active" <?php echo ($status_id==1)?'checked':'' ?> name="status">
        <label for="active">Active</label>

        <input type="radio" id="on-leave" value="leave" <?php echo ($status_id==2)?'checked':'' ?>name="status">
        <label for="on-leave">On Leave</label>

        <input type="radio" id="terminated" value="terminated" <?php echo ($status_id==3)?'checked':'' ?>name="status">
        <label for="terminated">Terminated</label>
    </div>  
</div>

<div class="newrow">
    <label>Eligible for rehire?</label>
    <div class="radio-group">
        <input type="radio" id="yes" value="yes" <?php echo ($rehire_id==1)?'checked':'' ?>name="rehire">
        <label for="yes" class="radio_label">Yes</label>

        <input type="radio" id="no" value="no" <?php echo ($rehire_id==2)?'checked':'' ?> name="rehire">
        <label for="no" class="radio_label">No</label>
    </div>
</div>

</fieldset>   

The first thing I want to point out is that in the first row, I decide what to check based on $status_id . For this row if $status_id == 1 , the first radio button is checked. BUT if it equals 2 or 3, nothing gets checked.

But in the second row, I decide what to check based on $rehire_id. If $rehire == 2 , the second button is checked, BUT NOTHING happens if it equals 1.

WHAT is going on here? Any ideas?

You have no space between checked and the name tag in the cases where it's not working.

When $status_id==2 is true

value="leave" <?php echo ($status_id==2)?'checked':'' ?>name="status">

will output

value="leave" checkedname="status">

instead of what you expected

value="leave" checked name="status">

Add a space before each name=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM