0

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

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
<?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'];

?>

Comments

0

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

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

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

Comments

0

Instead of name="one" an option needs a

value="myvalue"

and your select tag needs an

name="nameofthisthinghere"

1 Comment

You're correct, but I'd like to point out that the value attribute is optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.