0

A user can enter an input value :

  1. by selecting one from a list (a json list is returned by file.php).
  2. or by typing one (we check if it exist with an ajax call, file2.php). If success (the value exist), then we call "geo".

The problem is that the "geo" function is called twice, because the change event is called after the select event.

Here is my code :

<input id="test">

$("#test").autocomplete({
    minLength: 2,
    source:  "file.php",
    select:function(event,ui){
        var name = ui.item.value;
        geo(name);
    },
    change: function (event, ui) {
        $.ajax({    
            type:'POST',
            async:false,
            url:'file2.php',
            data:{'name':$('#test').val()},
            success:function(r){
               o=JSON.parse(r);
               geo(o.name);
            }
        });
    }
});

I tried to add event.preventDefault(); like this :

select:function(event,ui){
            var name = ui.item.value;
            geo(name);
            event.preventDefault();
        },

but it doesn't work...

Any idea?

1
  • remove geo call from select and simply use select to set the name? either that or put in a check to the change event to see what fired it - e.g. var selectedName = '' and set that var with the select method instead of scoped 'name' and then check if $('#test').val() === selectedName and if so dont' run change ajax Jan 25, 2016 at 17:42

2 Answers 2

2

Example to try:

var selectedName = '';

$("#test").autocomplete({
    minLength: 2,
    source:  "file.php",
    select:function(event,ui){
        selectedName = ui.item.value;
        geo(selectedName);
    },
    change: function (event, ui) {
        if (selectedName === $('#test').val()) {
            return;
        }
        $.ajax({    
            type:'POST',
            async:false,
            url:'file2.php',
            data:{'name':$('#test').val()},
            success:function(r){
               o=JSON.parse(r);
               geo(o.name);
            }
        });
    }
});
0
0

I think the change & select callback is different with input element events change & select.

for autocomplete

selecting a list item trigger select, then change typing just trigger change

for input element

typing trigger "input/keyup/keydown/keypress" event, and when blur trigger "change" event

How about remove select callback here. Regardless of typing or selecting, change triggered anyway. If you don't wanna a checking on selecting, add a determine statements before ajax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.