简体   繁体   中英

How to select the dropdownlist value and validate it

I have created the dropdown list in my index page i want to select the one value from that list and validate it if not selected any value the code for that is as follows:

<form action="" method="post">
  <select value="state" name="state">
    <option selected="">---please enter---</option>
    <option value="1">andhra</option>
    <option value="2">thamil</option>
    <option value="3">kerela</option>
  </select>
</form>

php code for the above file is as follows:

<?php
if(!empty($_POST['state'])) {
  $state = $_POST['state'];
}
else {
  echo "required";
}
?>

I dont want to be select the first option in selection list please enter to be selected but the code which I have used is taking that value also I want relevant code how to validate that list?

I prefer adding a disabled attribute to the placeholder option, that way, a user has to choose something if they click the drop-down:

<select value="state" name="state">
    <option selected disabled>---please enter---</option>
    <option value="1">andhra</option>
    <option value="2">thamil</option>
    <option value="3">kerela</option>
</select>

Quick demo: http://jsfiddle.net/hxxJZ/

something like this should to the trick:

<form action="" method="post">
  <select name="state">
    <option value="0" selected>---please enter---</option>
    <option value="1">andhra</option>
    <option value="2">thamil</option>
    <option value="3">kerela</option>
  </select>
</form>

php

<?php
if( 0 != $_POST['state'] ) {
  $state = $_POST['state'];
}
else {
  echo "required";
}
?>

your HTML is not right, try edit this line

<option selected=""...

to this one

<option selected value="">---

select elements do not have an (HTML) value attribute, so remove value="state" .

The selected attribute should be selected="selected" (or just SELECTED ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM