Home > front end >  Using conditions in jquery append function
Using conditions in jquery append function

Time:06-15

Look at the code block below. Its working for me, but I need to write it with conditions. Condition mean, I need to add each span elements if item values is not empty.

create: function () {
  $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
  return $('<li >')
    .append('<div >'
            ' <span><span>' item.item_code '</span></span>'
            ' <span><span>' item.brand '</span></span>'
            ' <span><span>' item.stock '' item.unit '</span></span>'
            ' <span><span>' item.item_name '</span></span>'
            '</div>')                   
    .append('</li>')
    .appendTo(ul); 
}

So, I tried it in this way, But I coudn't figure it out.

create: function () {
  $(this).data('ui-autocomplete')._renderItem = function (ul, item) {

  var $li  = $('<li >');
  var $div = $('<div >');
  if (item.item_name) {
    $('<span><span>', {text: item.item_name}).appendTo($div); 
  }

  $div.appendTo($li);
  return $li.appendTo(ul); 
} 

Hope somebody may help me out. Thank you

CodePudding user response:

You can use the conditional (aka tertiary) operator:

 (item.item_name ? (' <span><span>' item.item_name '</span></span>') : '')
  • Related