1

I am using the jQuery autocomplete plugin like below. This works fine, but I'd like to loop through the values of the selected item. For example, if 'Product 1' were selected, I'd like to log this to the console:

label : Product 1
value : value1
tax   : 18%

I just cannot figure how to do this. If I do console.log(ui) I can see the values, but how do I loop through them? Can you please help?

<div class="input-group">
  <span class="input-group-addon">choices ...</span>
  <input type="text" class="form-control" placeholder="choice" name="choice" id="choice">
</div>
<div class="input-group">
  <span class="input-group-addon">value of choices ...</span>
  <input type="text" class="form-control" placeholder="" name="prid" id="prid">
</div>
$(function() {
  $("#choice").autocomplete({
    source: [{
        label: "Product 1",
        value: "value1",
        tax: "18%"
      },
      // These aren't fixed. Some products have, some less.
      {
        label: "Product 2",
        value: "value2",
        tax: "24%"
      }
    ],
    minLength: 1,
    delay: 0,
    select: function(event, ui) {
      event.preventDefault();
      $('#choice').val(ui.item.label);
      this.value = ui.item.label;
      $('#prid').val(ui.item.tax);
      // I'm stuck over here
      for (var i = 0; i < ui.length; i++) {
        console.log(ui[i]);
      }
    }
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
jmenezes
  • 1,888
  • 6
  • 28
  • 44
  • 1
    I don't understand the question. `ui.item` refers to the **single** object in the array relating to the option selected in the UI. As such there is nothing to loop over. You just access the properties as you already are in the preceding lines of code. – Rory McCrossan Jan 27 '20 at 15:38
  • If you do console.log(ui) you'll get (index):55 {item: {…}}item: {label: "Microsoft Windows 10", value: "MS WIN10", tax: "18%"}__proto__: Object. I'm trying to loop through that. – jmenezes Jan 27 '20 at 15:44
  • That's my point. It's a single object. There is nothing to loop through. – Rory McCrossan Jan 27 '20 at 15:45

1 Answers1

1

Your ui contains the following object

{
  "item": {
    "label": "Product 1",
    "value": "value1",
    "tax": "18%"
  }
}

If you want to loop over the keys then you use Object.entries

var uiEntries = Object.entries(ui.item)
for (var i = 0; i < uiEntries.length; i++) {
    var uiEntry = uiEntries[i];
    //uiEntry[0] = The key
    //uiEntry[1] = The value
    console.log(uiEntry[0] + ":", uiEntry[1]);
}

Alternatively, just log all the known keys, you will then get undefined for any value that doesn't exist

console.log("label : ", ui.item.label);
console.log("value : ", ui.item.value);
console.log("tax : ", ui.item.tax);

ButchMonkey
  • 1,873
  • 18
  • 30