开发者

How to mantain radiobutton, dropdown and checkbox values if submit fails PHP

I know how to it with text inputs.开发者_StackOverflow中文版 I can easily put a php script in its value, but doing it with input groups seems different. How can I mantain the values of group inputs if the submission of the form fails?


To re-mark a checkbox or radio button as checked, you use this code:

<input type="checkbox" name="foo" id="foo" checked="checked"/>

The key is checked="checked".

If you are using groups of checkboxes, make sure the name of the field ends with brackets [], like this:

 <input type="checkbox" name="foo[]" id="foo_1" value="1" checked="checked"/>
 <input type="checkbox" name="foo[]" id="foo_2" value="2" checked="checked"/>

Then your $_REQUEST['foo'] variable will automatically be an array of checked values. You can use in_array to see if a particular checkbox was checked.

Update based on comment

Here's how I would set it:

<input type="checkbox" name="foo[]" id="foo_1" value="1" <?= (isset($_POST['foo'] && in_array('1', $_POST['foo'])) ? 'check="checked"' : '' ?>/>

For single items (like radios), use this:

<input type="radio" name="foo" id="foo" value="1" <?= isset($_POST['radio]) ? 'check="checked"' : '' ?>/>

Hope that helps.

Update 2: Also, make sure you escape user input! Your example should look like this:

<input type="text" name="username" value="<?php if(isset($_POST['username']) echo htmlspecialchars($_POST['username']);?>">

Always assume the user is trying to hack your system, always escape user input!


Print the " checked" attribute for radio buttons and checkbox input tags, or the " selected" attribute for dropdown option tags.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜