简体   繁体   中英

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?

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']);
    })
});

You need to pass counter variable in your initIdStorageBinding function like,

function initIdStorageBinding(counter) { // pass counter here
  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']);
  });
}

Or make your counter variable global so that it can be accessible internally from any function.

Also in my opinion you should use class instead of binding every element from counter variable and its id like,

function initIdStorageBinding(){
  stringField = '.your-string-class';
  idField = '.other-field-class';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM