We have a jquery autocomplete input box:
<input name="suburb" id="suburb-agency" autocomplete="off" class="text" type="text" value="">
This drops down, and when they choose an option, another select box is updated depending on what was chosen:
<select class="text" name="state" id="state-agency">
<option value="notselected">Please select your state...</option>
<option value="Apple">Apple</option>
<option value="Pear">Pear</option>
</select>
Say for example they choose Pear in the #suburb-agency autocomplete, Pear is then selected automatically in #state-agency
That works perfectly.
The only problem I am having is jquery validation, when Pear is selected and the #state-agency box is changed, the validation doesn’t show, although it does if I manually select an option from the drop down box.
Here is my jquery:
/* STATE VALIDATION */
$("#state-agency").change(function () {
var state = $('#state-agency').val();
if (state == "notselected"){
$('#state-agency').css({"border-color":"#3399ff"});
$('#state-err').html("You must choose which state you work in.").removeClass("success_msg").addClass("error_msg");
return false;
}else{
$('#state-agency').css({"border-color":"#1f6d21"});
$('#state-err').html("Thanks for choosing your state!").removeClass("error_msg").addClass("success_msg");
}
});
How can I modify this so it shows the success message if it is selected from the autocomplete? and not just manually? I’m guessing I need to change from a change function?
Edit (our autocomplete code which updates the dropdown box as requested)
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split(term).pop();
}
$( "#suburb-agency" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "http://www.site.com/folder/script.php", {
term : extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
if (ui.item) {
$('#state-agency').val(ui.item.state);
}
else {
$('#state-agency').val('');
}
}
});
});
I’ve found a fix for this, I needed to use
trigger()on the relevent IDs in the autocomplete JS.