Forum Moderators: open

Message Too Old, No Replies

Javascript autocomplete submit

         

johnroberts2k

8:15 pm on Feb 2, 2022 (gmt 0)

5+ Year Member



I have the following javascript that returns a list of autocomplete values. Can anyone tell me how I can auto submit the form as soon as a user clicks on a name that shows in the display?


<form name="search" action="form.php" method="post">
<input type="hidden" id="user_id" name="username"/>
<div>Name: <input id="user_name" name="displayname"/></div>
</form>

$(function() {
$("#user_name").autocomplete({
source: [<?php echo $javaDataSource; ?>],
select: function(e, ui) {
$("#user_name").val(ui.item.label);
$("#user_id").val(ui.item.value);
return false;
}
});
});



I've tried the following two methods but still does not work:


$(function() {
$("#user_name").autocomplete({
source: [<?php echo $javaDataSource; ?>],
select: function(e, ui) {
$("#user_name").val(ui.item.label);
$("#user_id").val(ui.item.value);
$("#search").submit();
return false;
}
});
});




$(function() {
$("#user_name").autocomplete({
source: [<?php echo $javaDataSource; ?>],
select: function(e, ui) {
$("#user_name").val(ui.item.label);
$("#user_id").val(ui.item.value);
$("#search")[0].submit();
return false;
}
});
});

NickMNS

8:50 pm on Feb 2, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It's a bad idea, but easy to do.
You need to add an "on blur" or "on change" event listener to the input. On blur triggers when the input looses focus. On change triggers when the user change the value of the input. On blur is likely a better choice, but it really depends on what the user does after.


$("#user_name").on("blur", function(){
$("#search").submit()
});

Something like that, not sure about the exact syntax of jQuery as I don't use it.

The reason that it is a bad idea is that user will likely select the wrong items from the list, and will do this frequently, this in turn will submit the form. If this is an ajax request that isn't too bad, but you server will be get hammered for no reason as the user will likely make several selections before getting the right one (it is possible that this is desired, eg: populate some data and many selections are expected, so in that case it is not bad). But if the form is allowed to submit and a new page is loaded, that would really suck for the user and they will likely leave. Instead, add a submit button, this will give the user the chance to select another option if the wrong one is selected. Note that this is particularly bad with auto complete because the final result is not immediately clear to the user as that result is being populated as the user types.