ade123
ade123

Reputation: 2833

How best to pre populate a radio button selection using php?

I'm working on an application form.

It is to be pre populated with an individuals details, we already have their details. Basically we send them a link to their form, already populated with their details, we then simply ask them to check the form and hit submit if all info is correct.

I have the following to pre populate simple text boxes:

<input type="text" name="forename" id="input-forename" value="<?php echo htmlspecialchars(@$_REQUEST['forename']);?>"/>    

<input type="text" name="birthdate" id="input-birthdate" value="<?php echo htmlspecialchars(@$_REQUEST['date_of_birth']);?>" />

etc.

Everything works great with this.

I'm having difficulty with the radio buttons though.

This selection for example:

<label for="input-title-mr">Mr: <input type="radio" name="title" id="input-title-mr" value="Mr" /></label>
<label for="input-title-mrs">Mrs: <input type="radio" name="title" id="input-title-mrs" value="Mrs" /></label>
<label for="input-title-miss">Miss: <input type="radio" name="title" id="input-title-miss" value="Miss" /></label>
<label for="input-title-ms">Ms: <input type="radio" name="title" id="input-title-ms" value="Ms" /></label>

Would there be a good way of perhaps using the checked="" attribute and a php if statement to pre check the correct radio button?

Perhaps something along the lines of this:

<label for="input-title-mr">Mr: <input type="radio" name="title" id="input-title-mr" value="Mr" checked="<?php if ( @$_REQUEST['forename'] == 'Mr' ) { echo 'checked'; }?>" /></label>

I hope this makes sense and any help or advice would be greatly appreciated :)

Upvotes: 4

Views: 7053

Answers (2)

Matt Whitehead
Matt Whitehead

Reputation: 1801

Why not send along get vars in the link? Such as www.thelink.com?title=Mr.

Then use:

<label for="input-title-mr">Mr: <input type="radio" name="title" id="input-title-mr" value="Mr" <?php if($_GET['title'] == 'Mr') echo 'checked'; ?>" /></label>
<label for="input-title-mrs">Mrs: <input type="radio" name="title" id="input-title-mrs" value="Mrs" <?php if($_GET['title'] == 'Mrs') echo 'checked'; ?>" /></label>

etc...

Upvotes: 0

Ravi
Ravi

Reputation: 2086

<input type="radio" name="title" id="input-title-mr" value="Mr" <?php echo ($_REQUEST['title'] == 'Mr') ? 'checked="checked"' : ''; ?>  />

Upvotes: 4

Related Questions