2016-12-09 92 views
-1

我有一些城市名單在關聯數組在php中。我使用JavaScript「更改」來獲取每個項目的值。我想將項目設置爲默認項目(我想我將來會考慮使用地理位置)。PHP的JavaScript選擇與默認值

這裏我陣列:

// Array lists 
$city_array = array(
    array('id' => '1', 'name' => 'Aaaa'), 
    array('id' => '2', 'name' => 'Bbbb'), 
    array('id' => '3', 'name' => 'Cccc'), 
    array('id' => '4', 'name' => 'Dddd'), 
    array('id' => '5', 'name' => 'Eeee'), 
); 
$json_city = json_encode($city_array); 

而且我的PHP函數:

// Decode 
$cities = json_decode($json_city); 
function display_cities() { 
    global $cities; 
    $output = '<select id="citylists" onChange="onSelectCity()">'; 
    foreach($cities as $city) { 
     $output .= '<option class="itemcity" value="'.$city->id.'">'.$city->name.'</option>'; 
    } 
    $output .= '</select>'; 
    $output .= '<script type="text/javascript"> 
     function onSelectCity() { 
      var cityLists = document.getElementById("citylists"); 
      console.log(cityLists.value); 
     } 
     window.onload = function() { 
      onSelectCity(); 
     } 
    </script>'; 
    echo $output; 
} 

我想輸出是這樣的(在HTML打印):

<select id="citylists"> 
    <option class="itemcity" value="1">Aaaa</option> 
    <option class="itemcity" value="2">Bbbb</option> 
    <option class="itemcity" value="3" selected>Cccc</option> 
    <option class="itemcity" value="4">Dddd</option> 
    <option class="itemcity" value="5">Eeee</option> 
</select> 

,你可以看,我設置的默認值是<option class="itemcity" value="3" selected>Cccc</option>

我該怎麼做動態PHP循環內?

感謝

+1

http://stackoverflow.com/的更多鈔票重複問題/ 7571710 /選擇 - 動態默認值選擇 –

+0

嗨,謝謝你提醒:) – mrale81

回答

0

試試這個:

foreach($cities as $city) { 
    $selected = ($city->id == 3)?' selected ':null; 

    $output .= '<option class="itemcity" value="'.$city->id.'"'.$selected.'>'.$city->name.'</option>'; 
} 

順便說一句,對於有效的HTML你應該把它調整爲選擇= 「選擇」

+0

謝謝,它的工作。 :) – mrale81