mvasco
mvasco

Reputation: 5107

Changing select value using JQuery

I have a form with three dropdown combos. One of them shows a city name;

<div class="col-xs-2">
        <label for="name">Ciudad</label>
 <select class="form-control" id="ciudad_combo">
 <option>Selecciona Ciudad</option>
 </select>
  </div>

I am populating it using AJAX and PHP/MySQL.

But I also need to set a value if another condition is met.

I am trying to do it as follows:

if(components[component].types[0]=="locality"){
                var ciudad=components[component].long_name;

                $("#ciudad_combo").val("San Francisco");
            }

But the output changes from the initial value "Selecciona Ciudad" to nothing, the option appears to be empty.

Any help is appreciated.

Upvotes: 0

Views: 36

Answers (2)

Popnoodles
Popnoodles

Reputation: 28409

You need to add the option, and set is as selected

$('<option>').text('San Francisco').appendTo('#ciudad_combo').prop('selected', true);

https://jsfiddle.net/kpfy6nbr/

Upvotes: 2

Severino Lorilla Jr.
Severino Lorilla Jr.

Reputation: 1637

$('#ciudad_combo')
    .append('<option value="SF" selected="selected">San Francisco</option>')

Upvotes: 1

Related Questions