开发者

jQuery PHP select option

开发者 https://www.devze.com 2023-02-01 02:45 出处:网络
I have a list of genders to select. The default selection is \'select\' <select id="gender" >

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 g开发者_运维百科ender'


$("#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';
}


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


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.

0

精彩评论

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