'Textbox autocomplete clears if not match in option value
I have here an autocomplete function. What I need is if the value that writing in textbox is not match on option value clear the textbox. Here's what I got right now http://jsfiddle.net/qv94t/
The textbox not allowing even the value is in the options.
Here's my code
<form id="register_form" name="register_form">
<input list="language" id="none">
<datalist id="language" name="options">
<option value="Alabama">Alabama</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
<option value="kansas">kansas</option
<option value="California">California</option>
</datalist>
</form>
<script>
var validOptions = $("form#register_form input[name='options']").val();
previousValue = "";
$('#none').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function() {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
</script>
Solution 1:[1]
I think this is what you are looking for:
http://jsfiddle.net/juvian/qv94t/3/
Your validOptions was undefined, so was not working properly.
var validOptions =[];
$("#language option").each(function(){
validOptions.push($(this).val())
});
Hope it helps!
Solution 2:[2]
Get rid of this code
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
it is the one causing trouble
Demo Fiddle
Solution 3:[3]
just remove this.value = previousValue
here is updated fiddle, http://jsfiddle.net/qv94t/2/
var validOptions = $("form#register_form input[name='options']").val();
previousValue = "";
$('#none').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function() {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
//this.value = previousValue
} else {
previousValue = this.value;
}
});
Hope this helps..! :D
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Community |
Solution 3 | Ravi Dhoriya ツ |