Reputation: 93
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>
Upvotes: 0
Views: 1522
Reputation: 16068
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!
Upvotes: 2
Reputation: 4414
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
Upvotes: 0
Reputation: 9947
Get rid of this code
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
it is the one causing trouble
Upvotes: 1