Silco
Silco

Reputation: 59

Cannot get autocomplete field value

I have autocomplete field

$('.airport_field_destination').on('autocompleteselect', (event, ui) => {
  var id = Number($(this).attr('data-number'))

  $(`#search_legs_${id + 1}_origin_text`).val(ui.item.value);
  $(`#search_legs_${id + 1}_origin_id`).val(ui.item.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search[legs][0][destination_text]" id="search_legs_0_destination_text" value="London (LON), England" class="field-3 airport_field airport_field_destination ui-autocomplete-input" data-number="0" placeholder="Till" data-source="/autocomplete/destination/flight"
  data-id-element="#search_legs_0_destination_id" autocomplete="off">

But var id says NaN to me

Where is my trouble?

UPDATE

With event.target I'm able to get id. But ui.item.value show me undefined

Upvotes: 1

Views: 135

Answers (3)

Silco
Silco

Reputation: 59

So here is answer, how to do this

Thank's to @GeorgeBailey suggests for id

I can do it like this event.target and use arrow functions or make it like this

$('.airport_field_destination').on('autocompleteselect', function(event, ui){
  var id = Number($(this).attr('data-number'))

For ui.item- ui not have value

Here is console_log of ui - {item: {…}}item: {type: 1, id: 6540382, fullname: "London (LON), England", name: "London", city: "London", …}__proto__: Object

So Here is full working code

$('.airport_field_destination').on('autocompleteselect', function(event, ui){
  var id = Number($(this).attr('data-number'))
  console.log(ui);
  $(`#search_legs_${id + 1}_origin_text`).val(ui.item.fullname);
  $(`#search_legs_${id + 1}_origin_id`).val(ui.item.id)
});

Upvotes: 0

Muhammad Usman
Muhammad Usman

Reputation: 10148

You have two problems with your code. As you are using arrow function as callback on the event handler this is not here what you think.

So change this to event.target

Secondly, ui.item.value , I don't know what is this. But it looks like you are trying to get the value. So use $(ui).val() and that should work.

Your final script would look like something below

$('.airport_field_destination').on('autocompleteselect', (event, ui) => {
  var id = Number($(event.target).attr('data-number'))

  $(`#search_legs_${id + 1}_origin_text`).val($(ui).val());
  $(`#search_legs_${id + 1}_origin_id`).val($(ui).val());
});

Upvotes: 1

Jonathan Lam
Jonathan Lam

Reputation: 17371

The this event is undefined, because the arrow function does not capture the context (it uses the outside this context). If you use the function(event, ui) { ... } event handler syntax, then you will get the correct this.

Otherwise, you can use event.target as an alternative to this if you want to get the correct element, as @GeorgeBailey suggests.

Upvotes: 1

Related Questions