简体   繁体   中英

Linking 2 select lists that are on different pages in HTML

I have 2 php html forms, both consisting of 1 select list. In the first form, I have a select list that asks the user to select their State. According to the state selection on the first page, when the user clicks submit, the second selection list should show the postcodes for that state.

I am having difficulty in performing this task as they 2 select lists are on 2 different pages, i know how to use javascript if they are on the same but i am a bit stumped as they are on different pages. Im not sure how to link them together.

State* <select id="state" name="state"">
                         <option value="">Select</option>
                         <option value="OKC">OKC</option>
                         <option value="NYC">NYC</option>
                         <option value="CAL">CAL</option>

     </select><br />

So if the user selects OKC from first list on the first page, the second list on the second page should show only postcodes for OKC

If you absolutely need to have 2 different PHP pages for your select elements, you could use an HTTP parameter. For example you could have the first form have a submit button which takes you to the second PHP page:

firstpage.php:

<form action="secondpage.php" method="get">
    <select id="state" name="state">
         <option value="">Select</option>
         <option value="OKC">OKC</option>
         <option value="NYC">NYC</option>
         <option value="CAL">CAL</option>

    </select>

    <input type="submit" value="Next page" />

</form> 

The submit button would take your browser to the secondpage.php but according to your state selection, it would attach a parameter, for example secondpage.php?state=OKC .

On secondpage.php you could use the parameter to your advantage:

$state = $_GET['state'];

Use PHP statements to dynamically generate your <select> element:

 <?php

$state = $_GET['state'];

$postcodes = null;

if($state == "NYC")
{
    $postcodes = array("postcode1", "postcode2");
}

if($state == "OKC")
{
    $postcodes = array("postcode3", "postcode4");
}

?>


<form action="anotherpage.php" method="get">
    <select id="postcode" name="postcode">

        <?php

        foreach ($postcodes as $p) 
        {
            echo '<option value="'.$p.'">'.$p.'</option>';
        }

        ?>


    </select>

    <input type="submit" value="Next page" />

</form> 

Of course there are more efficient ways to go about this, but this should give you an idea.

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