简体   繁体   中英

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?

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

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