RedGiant
RedGiant

Reputation: 4748

JQueryUI autocomplete doesn't update its data-attribute from the select box

Example

$('select').change(function(){
      $('#auto').attr('data-id',$(this).val())
})

$('#auto').autocomplete({
    delay: 1000,
    source: function( request, response ) {  
            alert($(this.element).data('id'))
            return false
    }
 })

<select name="category">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>

<input id="auto" data-id="A" type="search"/>

I want to update the auto-input data attribute when someone select an option in the selectbox.

Is there any way to prevent the auto-complete input from caching its data attribute? The input is able to update the data-id the first time I change the option from A to B in the selectbox. But when I change from B to C, the input is still alerting B instead of C. Is $(this.element).data('id') not an appropriate way of getting the latest data attribute?

Upvotes: 0

Views: 75

Answers (1)

BeardedMan
BeardedMan

Reputation: 394

what about picking the value directly from the select control, like this:

$('#auto').autocomplete({ 
   delay: 100,
   source: function( request, response ) {  
      var selected = $('select[name="category"] option:selected'), 
          isSomethingSelected = selected.length == 1,
          selectedVal = isSomethingSelected ? 
                        selected.val() :  
                        $('select[name="category"] option:first').val();
      alert(selectedVal);
      return false;
   }
});

see JSFiddle

Upvotes: 1

Related Questions