makapaka
makapaka

Reputation: 179

cant change text value in jquery autocomplete

I have 3 elements; suburb, postcode, state:

<div class="field">
<input class="input-text round-border" type="text" name="suburb" id="suburb" size="40" validate="required:true" value="<?=$_POST['suburb']?>" /><br />
<label class="error" for="suburb">This field is required</label>
</div>

<label for="postCode" class="mandatory <?=$errors['postCode']?>">Postcode:</label>
<div class="field"><input class="input-text round-border" type="text" name="postCode" id="postCode" size="20" validate="required:true" value="<?=$_POST['postCode']?>" /><br />
<label class="error" for="postCode">This field is required</label> </div>

I'm using jquery autocomplete to successfully display a list of options in the suburb field:

enter image description here

You can see its split by comma, so I am then splitting those values up and putting them in their respective fields - ie, "VIC" goes to state field, "3088" goes to postcode - these work as you can see below, but also as you can see, I cannot get the suburb to set correctly:

enter image description here

So the code in the 'select' of the jquery is ( i wont put the whole thing in for sake of brevity):

messages: {
            noResults: '',
            results: function() {}
        },
        select: function (event, ui) {
            $subpost = ui.item.value.split(", ");

            $("#postCode").val($subpost[2]);
            $("#state").val($subpost[1]);
            $("#suburb").val($subpost[0]);

            //alert('suburb = ' + $subpost[0]);
        }

So the code is the same for all 3 fields, but for some reason the suburb itself just wont change. You can also see the //alert function which correctly displays the suburb by itself but it just wont set in the field ?

Upvotes: 0

Views: 1120

Answers (1)

James Thorpe
James Thorpe

Reputation: 32212

I suspect that the select event runs before the autocomplete actually sets the value of the input, so when your event handler sets the value, it's almost immediately overwritten.

What you can do is use setTimeout with a timeout of 0 to move your code to the end of the execution queue, so that the rest of the jQuery autocomplete code runs to completion before you attempt to set the value:

select: function (event, ui) {
    setTimeout(function() {
        $subpost = ui.item.value.split(", ");

        $("#postCode").val($subpost[2]);
        $("#state").val($subpost[1]);
        $("#suburb").val($subpost[0]);
    }, 0);
}

Using setTimeout with a 0 timeout is a fairly common approach to queuing code up in this fashion.

Upvotes: 4

Related Questions