jquery - How to use ternary operator in JavaScript? -


my case this:

... success:function(data) {     jquery.each(data.searchcityresponse.nation.city, function(key,value) {         console.log(value.citycode);         city.append(jquery("<option value.citycod==\'ceb\')?\'selected\':\'\'></option>").val(value.citycode).text(value.cityname));     });     city.select2(); } ... 

i check in console: http://imgur.com/jio8nyk

this seems problem writing ternary

"<option value.citycod==\'ceb\')?\'selected\':\'\'></option>" string , it'll not parse variable or javascript operator.

also, there typo, citycod should citycode.

you can use concatenation + operator

"<option " + (value.citycode === 'ceb' ? 'selected' : '') + "></option>" 

or, selected status can kept in variable , variable can used.

var selected = value.citycode === 'ceb' ? 'selected' : ''; "<option " + selected + "></option>" 

you can use prop() set selected status.

$("<option />")     .val(value.citycode).text(value.cityname)     .prop('selected', value.citycode === 'ceb'); 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -