Skip to content Skip to sidebar Skip to footer

Get State Name From Drop Down List After Click Submit Button (part 3)

Cont. on Pass city name from php to js (part 2) State data json ($stateJsonObject): Array ( [0] => stdClass Object ( [stateId] => s1 [stateName] => Kuala Lumpur)

Solution 1:

If this is submitted on the same page, you could add the currently submitted entry and put a checked attribute inside the loop:

<form action="test3.php" method="post">
    State:
    <select name="state" id="state" onchange="showCity(this, 'city')">
        <option value ="">select one</option>
        <?php
            for($i = 0; $i < count($stateJsonObject); $i++)
            {
                $selected = ($stateJsonObject[$i]->stateId == $_POST['state']) ? 'checked' : '';
                echo "<option value='".$stateJsonObject[$i]->stateId."' $selected>";
                echo $stateJsonObject[$i] -> stateName;
                echo '</option>';
            }
        ?>
    </select>
    <input type="submit" name="submit" value="Submit" />
</form> 

Or with a foreach variant:

foreach($stateJsonObject as $state) {
    $stateId = $state->stateId;
    $stateName = $state->stateName;
    $selected = ($stateId == $_POST['state']) ? 'checked' : '';
    echo "<option value='$stateId' $selected>$stateName</option>";
}

Post a Comment for "Get State Name From Drop Down List After Click Submit Button (part 3)"