I'm following the Railscast on this topic, and although the autocomplete feature works, I am unable to get it to submit the form when the user selects an item and presses enter. I have this (coffeescript) code but it doesn't seem to work... can anyone see where I'm going wrong please?
jQuery ->
$('#search_bar').autocomplete(
source: $('#search_bar').data('autocomplete-source')
).keydown (e) ->
$('#search_button').trigger "submit" if e.keyCode is 13
Ideally I would like it to submit on selecting an item via a mouse click too - but not sure if that's possible?
Update: I've tried this...
jQuery ->
$('#search_bar').autocomplete
source: $('#search_bar').data('autocomplete-source'),
select: (event, ui) ->
$(this).parents("form").submit()
...and although it now works if you use the keyboard to select an item (and press enter), if you select an item via a mouse click it only sends the string that you had typed and not the complete word from the auto-complete drop-down. (I guess what I need is for the search field to be updated with the contents of the text on mouse-over?)
Update 2: Sorted! Just add this onto the end
focus: (event, ui) ->
$('#search_bar').val(ui.item.value)
Use the select event. documentation here The enter key is caught by autocomplete to close the menu and intentionally does not propagate. The select event will fire for both the enter key and mouse select. However when clicked the form will be submitted before the label has a chance to change, so have to set that value first. Depending on your data source you may want to use item.label instead of item.value.
$('#search_bar').autocomplete({
source: $('#search_bar').data('autocomplete-source'),
select: function(event, ui) {
$(this).val(ui.item.value);
$(this).parents("form").submit(); // this will submit the form.
}
})
I believe the coffeescript would look like this
$('#search_bar').autocomplete(
source: $('#search_bar').data('autocomplete-source'),
select: (event, ui) ->
$(this).val(ui.item.value).parents("form").submit();
)
Don't know much about coffee script, but this is how I would do it in javascript
http://jqueryui.com/demos/autocomplete/
You can use the 'select' event. When the user selects something, do your submit:
$( ".selector" ).autocomplete({
select: function(event, ui) {
$('#theForm').submit();
}
});
I am fairly certain this will take care of both cases for you. Both onEnter and onClick.
Related
I have an input tag
<input type="text" name="cOperator" class="form-control scale-input operator" placeholder="Enter your ID" autocomplete="off" onkeyup="ajax_showOptions(this,'getEmp',event)" required>
So when I start typing in, it shows employee list. And I have a jQuery function that handles click event.
$( document ).on( "click",".optionDivSelected, .optionDiv", function() {
if($('.operator').val().length > 0){
$('.operator-li').next().addClass('active');
$( '.operator-li' ).find('span').addClass('hidden');
$('.operator-value').show();
$('.operator-value h1 span').html($('.operator').val());
$('.operator').parents('label').hide().parents('.fieldset').next().fadeIn();
}
});
function checks the value of input, hides an input, shows selected value in a div and brings to next step automatically(I don't have a next button).
This part works perfect.
Problem is: User can just navigate with tab, choose with down or up arrows and select with Enter keypress. I have a selected value in input but it doesn't bring me to next step because Click event wasn't fired. I tried to do something like below:
$( document ).on( "click, keypress",".optionDivSelected, .optionDiv", function() {console.log('someone used keyboard')});
but no luck. (I don't know if it's even possible to have multiple event handler)
How do I detect if user inserted value using Enter keypress and do my staff after.
it also creates me a problem when I validate input onchange. input wants to be typed not just inserted via click or enter keypress.
Please help me with this.
I can't show whole code. because it has a lot of backend staff mixed.
I'll include steps I am trying to achieve.
I start typing and I see a list:
I click one of option and I move to next step:
But when I select by hitting ENTER(or return) I just see input tag with selected option, no div with selected operator no next step. Just like below:
Update:
Below is my workaround and is not a question:
in combination of Aswin Ramesh's comment, alpeshandya and Vikash Mishra's answer I came up with this code and it does what I was expecting. and Most alpeshandya's answer helped me. Thank you guys.
And BTW If you see that I am somehow spagettiing the code, PLS let me know.:-)
var ajaxHandler = function(){
// $( document ).on( "click",".optionDivSelected, .optionDiv", function() {
if($('.operator').val().length > 0){
$('.operator-li').next().addClass('active');
$( '.operator-li' ).find('span').addClass('hidden');
$('.operator-value').show();
$('.operator-value h1 span').html($('.operator').val());
$('.operator').parents('label').hide().parents('.fieldset').next().fadeIn();
}
// });
console.log('ajaxhandler')
};
$( document ).on( "click",".optionDivSelected, .optionDiv", ajaxHandler)
$('.operator').on('keyup', function(event) {
if(event.which == 13) {
console.log("enter");
event.preventDefault();
ajaxHandler();
}
});
You will need to create a generic event handler function which can be used as handler for click as well as for key press. This should work for your usecase:
var eventHandler=function(){
if($('.operator').val().length > 0){
$('.operator-li').next().addClass('active');
$( '.operator-li' ).find('span').addClass('hidden');
$('.operator-value').show();
$('.operator-value h1 span').html($('.operator').val());
$('.operator').parents('label').hide().parents('.fieldset').next().fadeIn();
}
}
$( document ).on( "click",".optionDivSelected, .optionDiv", eventHandler)
$( document ).on( "keypress",".optionDivSelected, .optionDiv", function(event){
if(event.which == 13) {
eventHandler();
}
})
Here is plunker for demo:
demo
The body of my HTML looks like this:
<body>
<form action='http://www.example.com' method='GET'>
<input type='text' id="text_input"/>
</form>
</body>
After entering a couple values into the field and returning to the site, a user is given autocompletion suggestion from the browser. When you select one, how can I have the form automatically submit?
In this question, they show something similar in jQuery:
$("#text_input").autocomplete({
source: ['apple', 'banana'],
minLength: 2,
select: function(event, ui) {
$("#text_input").val(ui.item.value);
$("#text_input").closest('form').submit(); }
});
However, this uses custom autocompletion suggestions, and not the browsers saved results.
Browser auto-completion isn't generally detectable using JS, from the scripts perspective, it will just appear that the user entered some data.
I think the best thing to do would be re-consider your approach to the problem, however if you defiantly want to do it this way:
The closest thing I can think of to what you're after would be to listen for key presses and changes, and a change that occurs with no key presses can be considered an auto-completion.
e.g.
$(document).ready(function(){
var keyPressed = false;
$("#test").on("keydown", function(){
keyPressed = true;
});
$("#test").on("change", function(){
if(!keyPressed){
alert("Submit");
}
});
});
Example: https://jsfiddle.net/o60nf4s6/
Issues:
Also triggered by pasting using the right click context menu
change event is only fired after the input field loses focus
Any keypress in the input will stop it from submitting, even if auto complete us used. This will only work if the whole input is filled from the browser options.
I have a checkout form where a zipcode is needed. I need this zipcode to get a LocationID. The zipcodes are in 0000XX format but i just need the first 4 digits. Now i have made a (global) javascript to get the locationID trough ajax.
The only problem is that now im using a keyup function that is activated when someone types in a zipcode. But i want it to be activated when a user has typed in something and clicks on another field. how can i do this ?
$('#deliveryzip').bind('keyup change', function(){
//Get zip
var zip = $('#deliveryzip').val();
//Strip first 4 chars from input
//check if 4 chars are integer
//if all ok do ajax...
//Get locationID from zipcode
$.post(jssitebaseUrl+'/ajaxFile.php',{"zip":zip,"action":"getLocInfo"},function(response){
if(response == "ok"){
alert(response);
//If return is ok..
var show = true;
}
});
if(show){
$('#locInfo').show();
} else {
$('#locInfo').hide();
}
return false;
});
Instead of listening to the keyup event, why don't you just listen to the change event?
$('#deliveryzip').on('change', function(){....});
The change event fires when an input field changed and once it looses focus (e.g. through the user clicking on another element). See http://msdn.microsoft.com/en-us/library/ie/ms536912(v=vs.85).aspx for more info (from Microsof) and here the documentation from Mozilla https://developer.mozilla.org/en-US/docs/Web/Reference/Events/change
You can use onBlur function : http://www.w3schools.com/jsref/event_onblur.asp
The onblur event occurs when an object loses focus.
Onblur is most often used with form validation code (e.g. when the user leaves a form field).
Tip: The onblur event is the opposite of the onfocus event.
With jQuery : on( "blur", handler )
Change 'keyup change' to blur
Blur is essentially the opposite of focus
Documentation here
I have a really simple problem that I am struggling to find a solution for.
Basically I have an ASP.NET textbox declared as such.
<asp:TextBox runat="server" ID="txtCourse" CssClass="input-xlarge HighlightibleField" placeholder=""></asp:TextBox>
Onto this textbox I have bound a the jQuery UI autocomplete widget like this.
$("#<% =txtCourse.ClientID %>").autocomplete({
source: ["Course1", "Course2", "Course3"],
select: function (event, ui) {
__doPostBack("<% =btnPostBacker.UniqueID %>", "");
}
});
The postback occurs as expected however the txtCourse.Text will not persist (or postback) the value that it was populated with.
So for example, I go ahead and select "Course1", the value is populated into the txtCourse textbox, the postback occurs and I view the value of txtCourse.Text and it will still be only the text that I have inputted using the keyboard (eg: "c").
I have tried setting a timer to delay the execution of the postback ever so slightly as such:
setTimeout(function () {
__doPostBack("<% =btnPostBacker.UniqueID %>", "");
}, 500);
And while this seems to work, I feel it shouldn't be necessary and have no idea why it is required.
What am I doing wrong? Any help would be sincerely appreciated.
Do you need to post the item selected?
select: function( event, ui ) {
__doPostBack("<% =btnPostBacker.UniqueID %>", ui.item);
}
EDIT: or perhaps:
select: function( event, ui ) {
$(this).val(ui.item);
__doPostBack("<% =btnPostBacker.UniqueID %>", "");
}
Requirement:
I'd like a jQuery autocomplete element that allows the user to pick an item and set the display field and a hidden field with the selected value. But I would also like the field and the hidden field to be cleared when the input field receives focus by the user.
Problem:
The problem I'm facing is that when the user selects an item it's almost like jQuery is executing the onSelect function and then sending the focus to the input field again which fires my focus() event (and therefore clearing my selection).
Problem Browser:
IE8 , works in Chrome. Did not try others.
Attempted fixes:
I have tried setting the focus to another element in the select()
function. It did put the focus on that element but only after
focussing on the input field
Tried both event.preventDefault() and event.stopPropagation() in the
select() method. Did not work.
Blur didnt work either.
Workarounds:
I guess I can change the clearing to be on click instead of on focus, but this is not what I want.
Similar stackoverflow thread:
jquery autocomplete remove focus after suggest
Code:
Here is my code:
$(function () {
$("#autosuggest").autocomplete({
source: "my server path",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autosuggest").val(ui.item.value);
$("#hidden").val(ui.item.id);
}
}
});
$("#autosuggest").focus(function () {
$("#hidden").val("");
this.value = "";
});
});
The problem is: when you click on an autocomplete suggestion, the focus shifts to that dropdown menu, ever so shortly, to return to your input afterwards. Do you still get this problem if you choose the autocomplete suggestion by using the arrow-down button? If you do not, then this is the problem.
The only way I can see to fix this is not to make it a focus event after all, but I think I know why you don't want to make it a click event: you also want to capture tabbing into the field.
Solution: make it a click handler, and add a 'keyup' handler that executes the click handler handler if the key was a tab (arrow-down etc are still allowed).
I got this from the jQuery forum and it works fabulous!
select: function(event, ui) {
$(event.target).autocomplete("close")
setTimeout(function() {
$(event.target).blur();
})
}
Link: https://forum.jquery.com/topic/autocomplete-input-field-stays-focused-after-selection
Try onSelect function..
$(function () {
$("#autosuggest").autocomplete({
source: "my server path",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autosuggest").val(ui.item.value);
$("#hidden").val(ui.item.id);
}
},
onSelect: function (suggestion) {
$(this).click();}
});
$("#autosuggest").focus(function () {
$("#hidden").val("");
this.value = "";
});
});