Reputation: 1479
I have a simple php contact form but cannot get the radio buttons to only choose only 1 option (selection required). Also not sure of the script needed for drop down box (this selection is not required)
//radio button individual or team required
if(trim($_POST['individual']) == '') {
$hasError = true;
} else {
$individual = trim($_POST['individual']);
}
//radio button individual or team required
if(trim($_POST['team']) == '') {
$hasError = true;
} else {
$team = trim($_POST['team']);
}
<input type="radio" name="individual" value="individual" id="individual" checked="checked">Individual</label>
<input type="radio" name="team" value="team" id="team" > Team</label>
<label for="shirt"> <strong>T-Shirt size (Optional)</strong></label>
<br />
<select name="Shirt Sizes" id="shirt">
<option value="small" name="small" id="small">Small</option>
<option value="medium" name="medium" id="medium" selected="selected">Medium</option>
<option value="large" name="large" id="large">Large</option>
<option value="xlarge" name="xlarge" id="xlarge">Extra Large</option>
</select>
Any help would be great. Cheers
Upvotes: 1
Views: 3213
Reputation: 15905
Radio buttons must have the same name if you want the browser to enforce the selection of only one of them
<input type="radio" name="quantity" value="individual" id="individual" checked="checked">Individual</label>
<input type="radio" name="quantity" value="team" id="team" > Team</label>
Then in PHP, you can check which was selected with:
if(isset($_POST['quantity'])) {
if($_POST['quantity'] == 'individual') {
// individual
} elseif($_POST['quantity'] == 'team') {
// team
}
}
Also, I'm not sure if this was just a product of copying and pasting, but you are missing opening label tags before both of your radio buttons.
Edit: This another minor thing not related to your question, but unless you have a specific need for it, your <option>
s don't need to have a name attribute. The value will do (and they don't need an id either unless you need an easy way to access them individually with JS).
Upvotes: 1
Reputation: 24383
You need to give the radio buttons in the same group the same "name" attribute:
<input type="radio" name="type" value="individual" id="individual" checked="checked">Individual</label>
<input type="radio" name="type" value="team" id="team" > Team</label>
That way when you click on one it will unselect the other one.
Upvotes: 0
Reputation: 33522
You need to name all your radio buttons the same for your browser to understand they are grouped.
<input type="radio" name="team" value="individual" id="individual" checked="checked">Individual</label>
<input type="radio" name="team" value="team" id="team" > Team</label>
When it is posted, the value
is sent under the variable name of the elements.
Upvotes: 1