Recently I was working on a project that required the "checked" value on a radio button. I had put the form item in a php loop to update products for a marketing site. I used the following code.

#phpLessons

Example of Checked Value For Radio Select

<label class="btn btn-info active"><input type="radio" name="optradio" id="optradio'" value="shipped" checked>Shipped</label>
This is supposed to automatically check that value. However, I put it in a loop like this.

Example of Checked Value in PHP Loop

$ct=2;
while ($row = $result->fetch_assoc()) {

echo '<label class="btn btn-info"><input type="radio" name="optradio" id="optradio'.$ct.'" value="processing" >Processing</label>
<label class="btn btn-info active"><input type="radio" name="optradio" id="optradio'.$ct.'" value="shipped" checked>Shipped</label>';

}

The Problem Of Checked Value In A PHP Loop

I was using AJAX to process the forms. So I did not need a form tag, right? Wrong! When you are wanting to auto select a checked value on radio input fields you must use the form tag.

Example Checked Radio Input Value in PHP loop

echo '<label class="btn btn-info"><input type="radio" name="optradio" id="optradio'.$ct.'" value="processing" >Processing</label>
<label class="btn btn-info active"><input type="radio" name="optradio" id="optradio'.$ct.'" value="shipped" checked>Shipped</label>';

Other examples of Using Checked Value for Radio Inputs

<label><input type="radio" id="foo" chcked="checked"></label>
<input type="radio" name="foo" value="" checked="checked" />
<input type="radio" name="imgsel" value="" checked>
References

Conclusion

So there you have it. Use a form tag when you are in a loop for radio input fields. Then you will be able to auto select your radio input.

Next Lesson


Sign Up To Comment