Home > Net >  how to write the code to make an exception for the non-disabled option in select field
how to write the code to make an exception for the non-disabled option in select field

Time:12-23

Foremostly i'm bad at explaining things, if you don't understand the problem i'll explain it with time and comments,so be patient. Problem i'm facing is when field is empty and its disabled value shows up,it shows the following error as it is not counted as empty.

    Undefined index: gender in C:\xampp\htdocs\test_gender.php

enter image description here

What i want is that when value is empty and disabled value shows up, it should show an error 'gender field is not selected'.So how to write the php code for that! ```

```
<form action="" method="POST">
<?php if(isset($_POST['submit'])){
    $gender = $_POST['gender'];
    echo"$gender";
    $role = $_POST['role'];
    echo "$role";
} ?>
<select name="gender">
    <option disabled selected value>Gender</option>
    <option>Male</option>
    <option>Female</option>
    <option>Others</option>
</select><br><br>
<select name="role">
    <option disabled selected value>Role</option>
    <option>Author</option>
    <option>Admin</option>
    <option>Others</option>
</select>
<button type="submit" name="submit">Submit</button>
</form>
```

```

Look at the code above, if nothing is selected and it shows gender. It is not counting itself as empty as disabled value is there. So how to write the code to make an exception for the non-disabled option. What i basically want is if disabled value shows up and one clicks on submit button, it should show an error like "no option selected". If still not understood lets discuss in comments. And i couldn't find similar questions any.

CodePudding user response:

Try this out:

<form action="" method="POST">
<?php if(isset($_POST['submit'])){
    if(isset($_POST['gender']) and $_POST['gender'] != '') {
        $gender = $_POST['gender'];
    } else {
        $gender = "Gender field is not selected";
    }
    echo"$gender <br/>";

    if(isset($_POST['role']) and $_POST['role'] != '') {
        $role = $_POST['role'];
    } else {
        $role = "Role field is not selected";
    }
        echo "$role <br/>";
} ?>
<select name="gender">
    <option disabled selected value>Gender</option>
    <option>Male</option>
    <option>Female</option>
    <option>Others</option>
</select><br><br>
<select name="role">
    <option disabled selected value>Role</option>
    <option>Author</option>
    <option>Admin</option>
    <option>Others</option>
</select>
<button type="submit" name="submit">Submit</button>
</form>
  •  Tags:  
  • php
  • Related