Cont. from Get state name from drop down list after click submit button (part 3)
-
State data json ($stateJsonObject)
Array ( [0] => stdClass Object ( [stateId] => s1 [stateName] => Kuala Lumpur) [1] => stdClass Object ( [stateId] => s2 [stateName] => Selangor) )
-
City data json ($cityJsonObject)
Array ( [0] => stdClass Object ( [cityId] => c1 [cityName] => Kajang [cityStateId] => s2 ) [1] => stdClass Object ( [cityId] => c2 [cityName] => Seputeh [cityStateId] => s1 ) [2] => stdClass Object ( [cityId] => c3 [cityName] => Shah Alam [cityStateId] => s2 ) [3] => stdClass Object ( [cityId] => c4 [cityName] => Klang [cityStateId] => s2 ) [4] => stdClass Object ( [cityId] => c5 [cityName] => Kepong [cityStateId] => s1 ) )
-
Code (test3.php)
<?php $cityState = array(); $cityName = array(); for($j = 0; $j < count($cityJsonObject); $j++) { $cityState[] = $cityJsonObject[$j] -> cityStateId; $cityName[] = $cityJsonObject[$j] -> cityName; } ?> <html> <head> <script type="text/javascript"> function showCity(state, target_id) { var stateId = state.options[state.selectedIndex].value; var target = document.getElementById(target_id); target.length = 0; target.options[0] = new Option('select one', ''); target.selectedIndex = 0; var cityState = <?php echo json_encode($cityState, JSON_HEX_QUOT) ?>; var cityName = <?php echo json_encode($cityName, JSON_HEX_QUOT)?>; for(k = 0; k < cityState.length; k++) { if(stateId == cityState[k]) { target.options[target.length] = new Option(cityName[k],cityName[k]); } } } </script> </head> <body> <form action="test3.php" method="post"> State: <select name="state" id="state" onchange="showCity(this, 'city')"> <option value ="">select one</option> <?php $select_sign = ''; for($i = 0; $i < count($stateJsonObject); $i++) { if($stateJsonObject[$i] -> stateId == $_POST['state']) {$select_sign = "SELECTED";}else{$select_sign = "";} echo '<option value = '.$stateJsonObject[$i] -> stateId.' '.$select_sign.'>'; echo $stateJsonObject[$i] -> stateName; echo '</option>'; } ?> </select> <br /> City: <select name="city" id="city"> <option value ="">select one</option> </select> <br /> <input type="submit" name="submit" value="Submit"/> </form> </body> </html>
My question is I choose Selangor from state drop down list, after that I choose Klang from city drop down list. After I click submit button, how should I keep Klang name in the city drop down list selected?