I have an HTML select with default value and I would like to keep Data on this select, if nothing was selected before, I would like to keep the first value like this :
HTML Side :
<select id="gender" name="gender" required>
<option selected disabled>Gender</option>
<option value="1">Male</option>
<option value="2">Female</option> </select>
PHP Side :
$_SESSION['post'] = $_POST;
// I first protected the data with html_entities
$_SESSION['post']['gender']=$this->_dataProtected['gender'];
// I redirect just for test (it works well with other values from input)
header('Location: ?page=children&action=add');
exit();
Javascript side :
$(window).on('load',function (){
var idGender = document.getElementById('gender').value = "<?php echo $_POST['gender'] ?? " $('#gender').val($('#gender option:first').val()) " ?>";
});
Thank you for your help
The result after submit the form : it fill my select with null value in the case I haven't choose an option and the same when I chose an option.
CodePudding user response:
You cannot get a value passed back from an disabled option. Since the selection is required, instead check if the returned value is NULL, then you know that nothing else was selected.
Example:
If (is_null($_SESSION['post']['gender'])) {
$_SESSION['post']['gender'] = 'Gender';
}
With this if/else, you're changing the variable to Gender (The selected disabled option) if the disabled option is "selected".
CodePudding user response:
Thanks you @Stoff,
After adding a value=""
to option selected, I changed the Javavscript to this :
var idGender = document.getElementById('gender').value = "<?php echo
$_SESSION['post']['gender'] ?? '' ?>";
And now, its works :D