How can I add a condition on the way of .append()?

91
December 11, 2017, at 9:06 PM

Here is my code:

$.each(cities.cities, function (i, item) {
    $('select#city').append($('<option>', {
        value: item.id,
        text : item.name
    }));
});

Now I need to add a condition on the way of appending. I mean I want to add selected attribute to that option which has the same item.id as city_id variable. How can I do that?

Answer 1

selected is boolean property - which can be the result of a conditional:

$.each(cities.cities, function (i, item) {
    $('select#city').append($('<option>', {
        value: item.id,
        text : item.name,
        selected: item.id === city_id
    }));
});
Answer 2

If your goal is to set the selected attribute only if item.id === city_id evaluates to true, one way of doing this is the following:

$.each(cities.cities, function (i, item) {
    /* Create a data object. */
    var data = {
       value: item.id,
       text : item.name,
    };
    /* Check whether the ids are equal. */
    if (item.id === city_id) data.selected = "";
    /* Use the data object to create the option and append it. */
    $('select#city').append($('<option>', data));
});

The above will produce:

<option value = "..." text = "..." selected/>

Snippet:

/* ----- JavaScript ----- */ 
var 
  city_id = 2, 
  cities = [ 
    {id: 1, name: "Amsterdam"}, 
    {id: 2, name: "Athens"}, 
    {id: 3, name: "Berlin"} 
  ]; 
 
$.each(cities, function (i, item) { 
  /* Create a data object. */ 
  var data = { 
     value: item.id, 
     text : item.name, 
  }; 
 
  /* Check whether the ids are equal. */ 
  if (item.id === city_id) data.selected = ""; 
 
  /* Use the data object to create the option and append it. */ 
  $('select#city').append($('<option>', data)); 
   
  /* Log the created option. */ 
  console.log($('select#city').children().last()[0]); 
});
<!---- HTML -----> 
<script src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<select id = "city"></select>

READ ALSO
Open skype chat

Open skype chat

I am using skype href to open skype chat, but chrome is asking choose application !

268
Nouislider setting range from variable

Nouislider setting range from variable

I'm using the nouislider (https://refreshlesscom/nouislider/) and I want to set up the range values from variables

278
Camera clicked images sent to rails server through the iPhone mobile browser are offset by particular dimensions

Camera clicked images sent to rails server through the iPhone mobile browser are offset by particular dimensions

I am dealing with a problem where images clicked through an iPhone camera and uploaded through the mobile browsers to a rails backend have a portion cutoff and are seemingly pushed out

143
Auto generate Image using javascript [on hold]

Auto generate Image using javascript [on hold]

What I want to achieve: 1Create a image 2

202