Reputation: 111
Inputs: "Room number", "Name".
Autocomplete source of the second Input is changing depend on the first Input's value.
How can I convert my long "if-else" conditions into the short and simple automatic script?
I tried to do this. Alert is working fine and returns appropriate variable. But it doesn't work for changing Autocomplete source.
Thanks!
<input id="First" Placeholder="Room number" />
<input id="Second" Placeholder="Name" />
<script>
var first_input = [
"first",
"second",
"third",
"fourth",
"fifth"
];
$("#First").autocomplete({
source: first_input
})
</script>
<script>
var default_room = [
"Default"
];
var first_room = [
"Glory",
"Dorris",
"Rebecca"
];
var second_room = [
"Will",
"Henry",
"Louie"
];
var third_room = [
"Kraig",
"Eddie",
"Frank"
];
var fourth_room = [
"David",
"Rex",
"Jordan"
];
var fifth_room = [
"Ben",
"Janet",
"Cassaundra"
];
$("#Second").autocomplete({
source: default_room
})
$("#First").on("change blur", function() {
if (this.value == "first") {
$("#Second").autocomplete('option', 'source', first_room)
} else if (this.value == "second") {
$("#Second").autocomplete('option', 'source', second_room)
} else if (this.value == "third") {
$("#Second").autocomplete('option', 'source', third_room)
} else if (this.value == "fourth") {
$("#Second").autocomplete('option', 'source', fourth_room)
} else if (this.value == "fifth") {
$("#Second").autocomplete('option', 'source', fifth_room)
} else {
$("#Second").autocomplete('option', 'source', default_room)
}
/*
var src_change = this.value + "_room";
alert (src_change);
$("#Second").autocomplete('option', 'source', src_change);
*/
})
</script>
Upvotes: 1
Views: 1212
Reputation: 337570
This simple way to do this would be to put the room arrays in to an object which is keyed by the value you expect the #First
autocomplete to have.
Also note that the change
or blur
events will not be raised by selecting an option from the autocomplete; you need to use the select
property of the configuration object to handle the selection event. Try this:
var rooms = {
"default": ["Default"],
"first": ["Glory", "Dorris", "Rebecca"],
"second": ["Will", "Henry", "Louie"],
"third": ["Kraig", "Eddie", "Frank"],
"fourth": ["David", "Rex", "Jordan"],
"fifth": ["Ben", "Janet", "Cassaundra"]
}
$("#Second").autocomplete({
source: ["Default"]
})
$("#First").autocomplete({
source: [
"first",
"second",
"third",
"fourth",
"fifth"
],
select: function(e, ui) {
var room = ui.item.value;
if (!rooms.hasOwnProperty(room))
room = 'default';
$("#Second").autocomplete('option', 'source', rooms[room])
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<input id="First" Placeholder="Room number" />
<input id="Second" Placeholder="Name" />
Upvotes: 1