Search code examples
javascriptjquerybindtypeahead.jsselected

Dynamic binding of typeahead select event (jQuery)


So I am currently creating a form that can be expanded dynamically. Each dynamically added row in the form contains an input field that displays suggestions using the jQuery typeahead plugin.

I am trying to bind the typeahead:selected even to each new rows corresponding input field. The event returns the suggestions name and its corresponding ID in the database.

function initIdStorageBinding(){
  stringField = '#INPUT_FIELD'+counter;
  idField = '#INPUT_FIELD_ID'+counter;

  $(stringField).bind('typeahead:selected', function(obj, data, name) {
      $(idField).val(data['id']);
      $(stringField).val(data['name']);
  }
}

This function is called whenever a now row is appended to the form where counter is the index for the current row.

Problem: The binding always inserts the values into the last input field that was added to the form, not the field that is currently selected.

Adding the binding non dynamic like:

function doBindings(){
  $('#INPUT_FIELD1').bind('typeahead:selected', function(obj, data, name) {
      $('#INPUT_FIELD_ID1').val(data['id']);
      $('#INPUT_FIELD1').val(data['name']);
  });

  $('#INPUT_FIELD2').bind('typeahead:selected', function(obj, data, name) {
      $('#INPUT_FIELD_ID2').val(data['id']);
      $('#INPUT_FIELD2').val(data['name']);
  });
}

works fine.

Any Ideas on how to solve that?


Solution

  • So after quite some time of trying things I switch strategies. The following piece of code gets the job done:

    $('.CLASS_OF_INPUT_FIELDS').each(function(index,element){
        $(element).bind('typeahead:selected', function(obj, data, name) {
            $(element).next('.CLASS_OF_HIDDEN_ID_FIELD').val(data['id']);
            $(element).val(data['name']);
        })
    });