简体   繁体   中英

jQuery: Textbox text change event after autocomplete?

I'm using jquery autocomplete plugin for a textbox:

$('#TargetArea').autocomplete({
    source: '@Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })'  
    });

It works fine. Now, I want to do is: when the textbox text changed, call an action to get data from database, then show the data in another div.

$('#TargetArea').change(function () {
       var url = "/My/Test";
       var target = $("#TargetArea").val();
       $.post(url, { Target: target }, function (data) {
           $("#resultId").html(data);
       });
   })

However, this change event never triggered. If I comment out the autocomplete part, then it works fine. Anyone knows what the problem is? or, How I should do this?

Thanks

I think you should use the change event of the autocomplete plugin.

See the documentation here: http://api.jqueryui.com/autocomplete/#event-change

Check it, I think it should works.

$( "#TargetArea" ).autocomplete({
  source: '@Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })',  
  change: function( event, ui ) {}
});

you can make this either

1 - Initialize the autocomplete with the change callback specified:

    $( '#TargetArea' ).autocomplete({
      source: '@Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })',
      change: function( event, ui ) {
       var url = "/My/Test";
       var target = $("#TargetArea").val();
       $.post(url, { Target: target }, function (data) {
           $("#resultId").html(data);
       });
      }
    });

or

2- Bind an event listener to the autocompletechange event:

$('#TargetArea').autocomplete({
    source: '@Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })'  
    });

    $( '#TargetArea' ).on( "autocompletechange", function( event, ui ) {
                            var url = "/My/Test";
                            var target = $("#TargetArea").val();
                            $.post(url, { Target: target }, function (data) {
                                    $("#resultId").html(data);
                                   });
                            });

This will be triggered when the field is blurred, if the value has changed.

Source : http://api.jqueryui.com/autocomplete/#event-change

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