-1

I have some city lists in associative arrays in php. I use javascript "on change" to get the value on each items. I want to set an item as default (I think I am considering using geo location in future).

Here my arrays:

// 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);

And my php function:

// 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;
}

I want the output is like this (printed in 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>

As you can see, I set the default value is <option class="itemcity" value="3" selected>Cccc</option>.

How can I do that inside dynamic php loop?

Thanks

2

1 Answer 1

0

Try this:

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

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

By the way, for valid HTML you should change it to selected="selected"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.