I have a list of genders to select. The default selection is ‘select’
<select id="gender" >
<option value="select" selected>Select:</option>
<option value="1">Male</option>
<option value="0">Female</option>
</select>
in jQuery:
$.post( 'register.php, {
telp: $("#telp").val(),
postcode: $("#postcode").val(),
gender: $("#gender option[value='select']").attr('selected','selected')
}, ...
in PHP
$gender = $_POST['gender'];
if($gender == '') {
echo 'Please select gender';
}
I want either ‘Male’ or ‘Female’ to be selected not the default value.
if default option value ‘select’ is selected, it will echoing the error .. ‘Please select gender’
$("#gender option[value='select']").attr('selected','selected')this selects the option element with the value select. And make that the selected option. So whenever this code is executed the default value will be selected automaticly.If you want the textnode of the selected element then use
$("#gender option:selected").text()or$("#gender option:selected").val()to get the value (0 or 1). In your php code, use thisEven better is to check for the right value.