Change Dynamic field of Typeahead

1.5k views Asked by At

I'm programming a form with dynamic typeaheads fields, and i have found a problem when i want to show and select the suggestions. I have two first fields, a input select and a input typeahead. When a option is selected, it's load a list of values in the input typeahead. The problem comes when i create(dynamically) a clone of this pair of fields and i want to get de list of values in the correct typeahead. I get the id of the field (idTypeAhead) when i focus in the field and i use it in the typeahead. This is the code:

//TYPEAHEAD 
$('input.typeahead').focus(function(){
    idTypeAhead = parseInt($(this).attr('id').replace('typeAhead_',''));
    selectAttr = $('select#selectAttr_'+idTypeAhead).find('option:selected').val();
    if(selectAttr=="null"){
        selectAttr=0;
    }       
});

$("input#typeAhead_"+idTypeAhead).on("typeahead:select").typeahead({
        name:'input#typeAhead_'+idTypeAhead,
        displayKey: 'input#typeAhead_'+idTypeAhead,
        input: 'input#typeAhead_'+idTypeAhead,
        container:'input#typeAhead_'+idTypeAhead,
        display: $(this),
        suggestion: $(this),
        minLength : 1, 
        sorter : this.query,
        source : function(query, process){
            return $.ajax({
            url:'/aplicaciones/jsonValorAttr?selectAttr='+selectAttr,
            dataType: 'json',
            type:'POST',
            success: function(data){                    
                states = [];     
                map = {};  
              $.each(data, function (i, state) {         
                    map[state] = state;         
                    states.push(state); 
                    });       
            process(states);
            }
          });
        }
      });

I have this code in form (i use Spring STS). Also i have two buttons "+" and "-". When i click "+", i clone this two fields and increase de id number of each element. When i click "-", i remove a pair of fields. (example: selectAttr_101 ->newclone: selectAttr_102).

<div class="controls">
        <form:select path="rolHerramientaID" id="selectAttr_101" cssClass="field-required lstAtributos" cssErrorClass="select-error">
        <form:option value="null" selected=""><spring:message code="altaAplicacion.form.seleccionar" />
        </form:option>
        <c:forEach var="selectAtributos" items="${resultAtributos}" varStatus="rowCount">
        <form:option value="${selectAtributos.atributosId}">${selectAtributos.nombreAtributo}</form:option>
        </c:forEach>
        </form:select>
        <form:errors path="rolHerramientaID" class="help-block" /></div>
</div>

<div class="control-group required">
        <label for="input01" class="control-label"><spring:message code="altaAplicacion.form.valor" /></label>
        <div class="controls">
        <input id="typeAhead_101" class="input-medium typeahead" type="text"  data-provide="typeahead" autocomplete="on">
 </div>

How can i change the container of the typeahead dynamically?

2

There are 2 answers

0
Sandro Martins On

I've been searching for the solution for this problem and found your post, with some small changes that worked for me.

I've stated the fixed input field in the form as typeAheadId_1 and created a function before create the typeahead object to manipulate the typeahead index. on the insert operation, I increase the counter and destroy the typeahead object before each dynamic fields wrapping and recreate the typeahead object (passing the counter) after the fields creation.

For edition (some dynamic fields are created direct in the form), I've created a REST service to return how many fields were wrapped and start counting from this.

It worked perfect for me.

If you didn´t solve or need some help, please let me know!

0
Sachin Vairagi On

Following codes are working for me -

var typeaheadSettings = {
  source: function (query, result) {
      $.ajax({
              url: "{{url('/work-order/get_parts_suggestion')}}",
              data: 'txt=' + query,            
              dataType: "json",
              headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
              type: "POST",
              success: function (data) {
                result($.map(data, function (item) {
                    return item;
                }));
              }
      });
  }
};

$('.typeahead').typeahead(typeaheadSettings); /* init first input */

$('.typeahead').on('added',function(){
  $('.typeahead').typeahead(typeaheadSettings);
});

add this line after appending/creating dynamic element -

$('.typeahead').trigger('added');

Reference - https://www.bootply.com/61431