简体   繁体   中英

Select tag not showing the selected option

Currently I'm loading in my select options inside my controller through an AJAX call. Now all the options are loading in correctly and I'm working on the edit page where it should display the option in my database as the selected value. To do this I'm using the following in my controller class:

public function getProperties($id){
    $option = "<option value='0'>Select</option>";

    $propertyList = $this->listings_model->get_array_property('');  
    $property = $this->listings_model->get_property($id);  
    foreach($propertyList as $m){
        $option .= "<option value='".$m['id']."' '".$property[0]['property'] == $m['id'] ? 'selected=selected':''."'>".$m['name']."</option>";
    }

    echo json_encode($option);
}

Over here $propertyList shows all the values and $property shows the particular selected value in the database. Now if I do this without the selected attribute part it shows all my values, but when I add the selected attribute, it shows me nothing and not even the selected value. I have checked my response for this in debugger and it looks like this:

"<option value='0'>Select<\/option>'>1095 Residence<\/option>'>118 Downtown<\/option>'>18 Burj Boulevard<\/option>"

Basically for every start of the option tag it only shows '> and I'm not sure how to fix this

You should surround your ternary operator with parentheses to set it's scope:

$option .= '<option value="' . $m['id'] . '"' . ($property[0]['property'] == $m['id'] ? ' selected="selected"' : '') . '>' . $m['name'] . '</option>';

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