Reputation: 951
I have an html search form with a single input. in the input field the user can write three different things: area name, trek name, other keywords.
my problem is:
I want the search to send the user to the area page if the user selects the area name from the list. jquery autocomplete has the select prop. does datalist has something similiar? maybe there's an option the autocomplete will load from two different resources? (one client and one server)
<form action="" method="get">
<input class="auto" name="desc" list="areas" />
<button type="submit">seatch</button>
<datalist id="areas">
<option id="area1" value="area1" >1</option>
<option id="area2" value="area2" >2</option>
<option id="area2" value="area2" >2</option>
</datalist>
</form>
script:
$('.auto').autocomplete({
source:"php/autocomplete.php",
minLength:1,
select: function(event,ui){
changePage('content/trek.php', {
Trek_Id:ui.item.Trek_Id
});
}
});
Thanks in advance Chaim
Upvotes: 3
Views: 2735
Reputation: 27600
Unfortunately the support for datalist
is still mediocre at best, and there are no events for this element specifically. Your best option is to compare the value of the input it's bound to with the available options in the datalist. If a match is found you can use that information to go to the area url instead of submitting the form.
You already use jQuery so I wrote a quick solution:
$('form').submit(function(e) {
var $input = $(this).find('input.auto');
val = $input.val();
list = $input.attr('list'),
match = $('#'+list + ' option').filter(function() {
return ($(this).val() === val);
});
if(match.length > 0) {
e.preventDefault();
var area = match.val();
alert('Navigate to ' + area);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="get">
<input class="auto" name="desc" list="areas" />
<button type="submit">seatch</button>
<datalist id="areas">
<option id="area1" value="area1" >1</option>
<option id="area2" value="area3" >3</option>
<option id="area2" value="area2" >2</option>
</datalist>
</form>
On submit this will check if the value in the input exactly matches the value of a datalist option. If so it will show an alert (replace that with your function of choice), otherwise it will just submit the form.
Upvotes: 0