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();
}
});