PWaddict Posted November 10, 2015 Share Posted November 10, 2015 Hello again How can I set a default checked radio button within foreach loop? By simply including "checked" within input code, only the last option gets checked but I would like to have the first option as checked. Thanks in advance! Link to comment Share on other sites More sharing options...
kongondo Posted November 10, 2015 Share Posted November 10, 2015 (edited) $i = 0;//set counter $out =''; $checked = ''; foreach($foo as $bar) { if($i == 0) $checked = "checked" //radio button stuff here...+ stuff with $bar... $out .= "<input type='radio' name='my_radio' value='{$bar}' {$checked}>"; $i++; } echo $out; Edited November 10, 2015 by kongondo typos 1 Link to comment Share on other sites More sharing options...
adrian Posted November 10, 2015 Share Posted November 10, 2015 We really need to see some code, but the general principle is to set up a counter and and if it equals 0 (the first loop), then add the "checked", eg: $items = $pages->get(1)->children(); $i=0; foreach($items as $item) { echo '<input type="radio" name="items" value="'.$item->name.'" ' . ($i==0 ? "checked" : "") . ' /> ' . $item->title; $i++; } Note the ternary operator checking to see if $i == 0 before outputting checked. EDIT: Well and truly beaten by Kongondo Link to comment Share on other sites More sharing options...
PWaddict Posted November 10, 2015 Author Share Posted November 10, 2015 Thank you very much guys. Great community! 1 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now