AnchovyLegend
AnchovyLegend

Reputation: 12537

Using select dropdowns in a form

I am trying to use HTML select dropdowns to help sort the search results on my website and I am having some trouble. In the code below, I specifically select Option1 and when I try to echo the result after I submit the form, it always echo's 'FAIL'. I was wondering if someone can help me understand what I am doing wrong and what is the proper way to retrieve the data from the option the user selected, after the form was submitted?

<?php 

echo '<form method="post" action="search.php">
    <select>
         <option name="one">Option1 </option>
             <option name="two">Option2</option>
        </select>
        <input type="text" name="searchword" />
        <input type="submit" value="Search"  />
</form>';



if(isset($_POST['one'])){
     echo 'Option1 is set';
}else{
     echo 'FAIL';
}

?>

thank you

Upvotes: 0

Views: 114

Answers (4)

<?php 

echo '<form method="post" action="search.php">
    <select name="my_option">
         <option value="one">Option1 </option>
             <option value="two">Option2</option>
        </select>
        <input type="text" name="searchword" />
        <input type="submit" value="Search"  />
</form>';



echo "My option value is : " .  $_POST['my_option'];

?>

Upvotes: 1

Ayush
Ayush

Reputation: 42440

This is because the name attribute goes with the select tag.

<select name="dropdown">
    <option>Option 1</option>
    <option>Option 1</option>
</select>

if(isset($_POST['dropdown'])) {
    echo $_POST['dropdown']; //echoes 'Option 1'
}

If you like, you can add a value attribute to the option element, but you don't have to.

If you do

<option value="foobar">Option1</option>

The form will post foobar and not Option1.

Upvotes: 3

Sliq
Sliq

Reputation: 16494

Instead of name="one" an option needs a

value="myvalue"

and your select tag needs an

name="nameofthisthinghere"

Upvotes: 0

ilanco
ilanco

Reputation: 9957

You need to name your select tag and access that instead.

<select name="options"></select>

echo $_POST['options']; will give you your selected option

Upvotes: 0

Related Questions