Bendy
Bendy

Reputation: 3576

jQuery UI autocomplete object not returning anything

I am having problems trying to get an autocomplete field populating with AJAX. One account user can have multiple members associated to it.

I have taken a step back by manually defining the array to get it working but something is still wrong. I assume it's something in my jQuery UI script as it's a big question mark for me at the moment.

The functionality I'm trying to create is that the user can start entering the name of a member (eg Smith, John) and selects it, the page will impersonate the user and reload the same page but appending the path with (in the example of Smith, John it would return ?_switch_user=jsmith)

HTML code:

<form class="navbar-form navbar-left" role="search">
   <div class="form-group">
      <input type="search" id="search-names" class="form-control" placeholder="Enter member name">
   </div>
   <button type="submit" class="btn btn-default">Submit</button>
</form>

jQuery UI script:

var UserArray = [
  { "label": "Smith, John", "value": "jsmith" },
  { "label": "Doe, Jane", "value": "jdoe1990" }
];

$( "#search-names" ).autocomplete({
  source: UserArray,
  minLength: 2,
  change: function() {
    var UserArray = $(this).val();
    if (!UserArray) return;

    window.location = window.location + '?_switch_user=' + UserArray.value
  }
});

Upvotes: 0

Views: 87

Answers (2)

Jorrex
Jorrex

Reputation: 1500

It's pretty simple what is wrong with your code.

1) You're using UserArrayfor your array of objects, but in the change() function, you declare another variable with the same name. This should be different from each other.

2) the property names in your objects shouldn't be enclosed with "".

See the code below or in this fiddle

HTML

<form class="navbar-form navbar-left" role="search">
  <div class="form-group">
  <input type="search" id="search-names" class="form-control" placeholder="Enter member"/>
  </div>
  <button type="submit" class="btn btn-default">
  Submit
  </button>
</form>

jQuery

var userArray = [
  {
    label: "Smith, John",
    value: "jsmith"
  },
  {
    label: "Doe, Jane",
    value: "jdoe1990"
  }
];

$("#search-names").autocomplete({
    source: userArray,
  minLength: 2,
  change: function() {
    var user = $(this).val();
    if(!user) return;

    window.location = window.location + "?_switch_user=" + user;
  }
})

Upvotes: 1

vorillaz
vorillaz

Reputation: 6296

This should do the trick:

$("#search-names").autocomplete({
    source: UserArray,
    minLength: 2,
    select: function(event, matched) {
        console.log(matched)
        window.location = window.location + '?_switch_user=' + matched.item.value
    }
  });

Demo

Upvotes: 1

Related Questions