0

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'

1
  • Please post your actual code next time. This code (JS part) has syntax errors and is not working as it is. Commented Dec 27, 2010 at 15:16

3 Answers 3

1

$("#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 this

$gender = $_POST['gender'];
if($gender == 'select' || $gender = 'Select:') {
   echo 'Please select gender';
}

Even better is to check for the right value.

$gender = $_POST['gender'];
if($gender != 'Male' && $gender != 'Female') {
   echo 'Please select gender';
}
if($gender != 1 && $gender != 0) {
   echo 'Please select gender';
}
Sign up to request clarification or add additional context in comments.

Comments

1

$( '#gender option:selected' ).val () will give you the value of the selected option in your select box.

Comments

0

According to what you've posted, you're always grabbing the "absent" value of the gender drop-down. I believe what you're looking for, as a selector, is '#gender option:selected' which will grab the selected option.

Remember that the value field is what is going to be sent to your PHP page. I would advise to check if the drop-down is still set to selected (as a .val()) and bring the user's attention back to it before form submit so they can make an actual choice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.