Home > Software engineering >  Select tag not showing the selected option
Select tag not showing the selected option

Time:12-05

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

CodePudding user response:

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>';
  • Related