BobCreativeDu
BobCreativeDu

Reputation: 39

Get selected option from the tag <select> in php to use on if

I tried this code:

<select name="selectedOption">
    <option value="select">  Select  </option>
    <option value="option1">  option 1  </option>
    <option value="option2">  option 2  </option>
</select>
<?php $selectedOption = $_POST['selectedOption']; ?>
<?php if($selectedOption == "option1") : ?>
    <a href="#">This will only display if option 1 selected</a>
<?php elseif($selectedOption == "option2") : ?>
    <a href="#">This will only display if option 2 selected</a>
<?php endif; ?>

But I get errors when I'm testing it on the web. The error that apears is "Notice: Undefined index: selectedOption in C:\wamp\www\vilaLuz\index.php on line 40"

What I am trying to do is get the option from the select and put a text under if option 1 is selected and a different text under if option 2 is selected, is that possible?

Upvotes: 0

Views: 109

Answers (4)

rrtx2000
rrtx2000

Reputation: 636

You should check to see if $_POST['selectedOption'] is set and is not empty. Empty() does these tests for you.

<?php
if (!empty($_POST['selectedOption'])) {
    $selectedOption = $_POST['selectedOption'];
    if($selectedOption == "option1") {
        echo('<a href="#">This will only display if option 1 selected</a>');
    }
    elseif($selectedOption == "option2"){
        echo('<a href="#">This will only display if option 2 selected</a>');
    }
}
?>

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

You need to first check whether $_POST['selectedOption'] exists using isset:

<?php
    $selectedOption = isset($_POST['selectedOption'])
                    ? $_POST['selectedOption']
                    : false;
?>

This is a ternary if statement which sets the value of $selectedOption to either the value of $_POST['selectedOption'] if it is set, or false if it isn't.

Upvotes: 0

Canser Yanbakan
Canser Yanbakan

Reputation: 3870

If you have not send your form, $_POST['selectedOption'] will be not set and empty!

So;

<?php $selectedOption = (!empty($_POST['selectedOption']) ? $_POST['selectedOption'] : ''); ?>

Upvotes: 0

Su4p
Su4p

Reputation: 865

<form action="" method="POST">
<select name="selectedOption">
    <option value="select">  Select  </option>
    <option value="option1">  option 1  </option>
    <option value="option2">  option 2  </option>
</select>
<input type="submit" value="post"/>
</form>
<?php if(isset($_POST['selectedOption'])) : ?>
<?php $selectedOption = $_POST['selectedOption']; ?>
<?php if($selectedOption == "option1") : ?>
    <a href="#">This will only display if option 1 selected</a>
<?php elseif($selectedOption == "option2") : ?>
    <a href="#">This will only display if option 2 selected</a>
<?php endif; ?>
<?php endif; ?>

Upvotes: 1

Related Questions