Chaining jquery keydown event - javascript

I am trying to create a drop down like functionality where a div is shown once somebody starts typing in the input box. I am able to attach mouse click event on the individual elements to select them. But I am not able to select them via pressing enter.
HTML
<input type="text" class="input" name="example" id="example" placeholder="example..." autocomplete="off" list="examplelist" />
<div class="autofill">
<ul class="autocomplete">
<li class="autocomplete-list">John Doe (San Jose, CA)</li>
<li class="autocomplete-list">Jane Doe (San Francisco, CA)</li>
<li class="autocomplete-list">John Jane (San Carlos, CA)</li>
</ul>
</div>
JQuery
$(document).ready(function () {
var $listItems = $('li.autocomplete-list'),
$div = $('div.autofill'),
$input = $('#example');
$div.hide();
$('input#example').on('keydown', function (e) {
var key = e.keyCode,
$selected = $listItems.filter('.selected'),
$current;
$div.show();
if (key != 40 && key != 38) return;
$listItems.removeClass('selected');
if (key == 40) { // Down key
if (!$selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
} else {
$current = $selected.next();
}
} else if (key == 38) { // Up key
if (!$selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
} else {
$current = $selected.prev();
}
}
$current.addClass('selected');
// When I press enter after selecting the li element
// Does not work :(
$current.on('keypress keydown keyup', 'li', function (event) {
if (event.keyCode == 13) {
var value = $(this).text().split('(')[0].trim();
$input.val(value) ;
$div.hide();
}
});
});
// If somebody clicks on the li item
$('li.autocomplete-list').on('click', function (e) {
var value = $(this).text().split('(')[0].trim();
$input.val(value);
$div.hide();
});
// change color on hover
$('li.autocomplete-list').hover(
function(){ $(this).addClass('hover') },
function(){ $(this).removeClass('hover') }
);
// When I press enter after selecting the li element
// Does not work :(
$('li.autocomplete-list').on('keypress keydown keyup', 'li', function (event) {
if (event.keyCode == 13) {
var value = $(this).text().split('(')[0].trim();
$input.val(value) ;
$div.hide();
}
});
});
How can I select a particular li element and then take its value when press enter? Here is the JSFiddle

The <li> element doesn't have focus, even though it's selected visually. The text input still has focus.
You need to check for the enter key on the text <input>. Not on the <li>
$('input#example').on('keydown', function (e) {
//...
var key = e.keyCode
if (key == 40) { // Down key
//...
} else if (key == 38) { // Up key
//...
} else if (key == 13) { // Enter key
//... make sure $current is not null
}
//...
}
Also be careful of this statement
if (key != 40 && key != 38) return;
Which will return from the event handler when the enter key is pressed.
Here's a fiddle: http://jsfiddle.net/q1vtwtdp/4/

Jordan P is correct, the handling of the list should all happen within the keydown handler function of the input.
$('input#example').on('keydown', function (e) {
var key = e.keyCode,
$selected = $listItems.filter('.selected'),
$current;
$div.show();
$listItems.removeClass('selected');
if (key == 40) { // Down key
if (!$selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
} else {
$current = $selected.next();
}
}
if (key == 38) { // Up key
if (!$selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
} else {
$current = $selected.prev();
}
}
if (key == 13) {
var value = $('.autocomplete-list').html().split('(')[0].trim();
$input.val(value);
$div.hide();
$current = $selected
}
$current.addClass('selected');
});
So you don't need:
$('li.autocomplete-list').on('keypress keydown keyup', 'li', function (event) {
if (event.keyCode == 13) {
var value = $(this).text().split('(')[0].trim();
$input.val(value) ;
$div.hide();
}
});
Working JSFiddle

Related

Datatable search result add to cart enter key

I have joined a script called jquery.mycart with datatable.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key == "Enter" || evt.key == "Enter");
} else {
isEscape = (evt.keyCode == 13);
}
if (isEscape) {
table.rows( { search:'applied' } ).data().each(function(value, index) {
console.log(value, index);
});
}
};
I have a problem that when we suppose we search for "Antalgina" when we press enter this search is added to the shopping cart. (look at the console).
Full code
https://codepen.io/anon/pen/oaQJNg
Please how could I do it or give me some hint
I hope you can help me.
Working codePen.
You could a simple jQuery event like :
$("document").on('onkeydown', function (e) {
if (e.keyCode !== 13) {
table.rows( { search:'applied' } ).data().each(function(value, index) {
console.log(value, index);
});
});
});

Open link in new tab with cmd-key?

I'm using this to click on an element to open a link. Is there a way to make it open a new tab when I hold the cmd-key down (and whatever that reflects in other OS)?
$(document).on('click', '.row', function(e) {
e.preventDefault();
window.location = '?id=' + $(this).data('id');
});
Basically the way a normal <a> works but via JS.
Try this:
$(document).on('click', '.row', function(e) {
e.preventDefault();
if (cmd) window.open('?id=' + $(this).data('id'), "_blank");
else window.location = '?id=' + $(this).data('id');
});
var cmd = false;
$(document).keydown(function(e) {
var key = e.which || e.keyCode;
if (key == 91 || key == 93 || key == 17 || key == 224) cmd = true;
});
$(document).keyup(function(e) {
cmd = false;
});
.row { border: 1px #000 solid }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">Click Me</div>
Sure, you just need to keep track of whether your target key(s) are being pressed in addition to your click handler:
document.querySelector('#test').addEventListener('click', function(e) {
if(cmdPressed) {
console.log('new tab');
// window.open('');
} else {
console.log('redirect');
// location.href = '';
}
})
// keeps track of whether user is pressing cmd key
var cmdPressed = false;
document.body.addEventListener('keydown', function(e) {
cmdPressed = e.which === 91;
});
document.body.addEventListener('keyup', function(e) {
cmdPressed = false;
});
<div id="test">
Click or CMD+Click me
</div>
or with jQuery:
$(document).on('click', '#test', function(e) {
e.preventDefault();
if(cmdPressed) {
console.log('new tab');
// window.open('');
} else {
console.log('redirect');
// location.href = '';
}
});
// keeps track of whether user is pressing cmd key
var cmdPressed = false;
$(document).on('keydown', function(e) {
cmdPressed = e.which === 91;
});
$(document).on('keyup', function(e) {
cmdPressed = false;
});

If the user presses the enter key, perform the same action as clicking the submit in Javascript

How do I get my enter key to perform the same action and my submit button?
I have my code here, and I would like the form to submit if the user presses submit, or presses the enter button on the keyboard
I have tried using if statements with keycode 13, but nothing is working for me.
Here is my Javascript code:
window.addEventListener('load', function(){
// Add event listeners
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(event) {
console.log('=' + event.target.className);
if(event.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(event.target.className.indexOf('completed'));
if(event.target.className.indexOf('completed') > -1) {
console.log(' ' + event.target.className);
event.target.className = event.target.className.replace(' completed', '');
document.getElementById('add-item').value='';
} else {
console.log('-' + event.target.className);
event.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
document.getElementById('new-item-text').value = "";
}
function removeItem(event) {
if(event.target.className.indexOf('remove') < 0) {
return;
}
var el = event.target.parentNode;
el.parentNode.removeChild(el);
}
function changeTitle() {
var title = prompt("change the title");
}
function handle(e){
if(e.keyCode === 13){
addItem();
}
return false;
}
});
You have to use the keydown event for this like below
document.onkeydown=function(evt){
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if(keyCode == 13)
{
//your function call here
}
Try adding this to your set of addEventListeners
document.getElementById('add-item').addEventListener('keydown', handle, false);

after keyup event I want the change to be permanent

I want to add a class to a list using keyup event but when the keyup event is called it add the class to the list. After some seconds, the class from the list will be removed then i try to use setinterval on the callback function. It work but if i try to navigate through the list it behave funny.
Here is the code
(function(){
var AutocompleteActivities = {
init: function(config)
{
this.config = config;
$("#keywords").on("keyup", this.confirm);
},
confirm: function(e)
{
var self = AutocompleteActivities;
var con = self.config.div;
key = e.keyCode;
press = e.timeStamp
//check whether there is a key up invent in the search textfield and up or down arrow is press
if(press != "" && e.keyCode == 40 || e.keyCode == 38)
{
if(con.css("display") == "block")
{
setInterval(function(){
self.navigation(key)},500)
}
}
},
navigation: function(key)
{
var con = this.config.div, // #options - the container of the autocomplete
li = con.find("ul").find(">li"),
totalLi = li.length,
firstLi = li.first(),
current = 1; // it should be zero for debug reasons it is one
if(key == 40)
{
if(current != 0) // check whether the autoComplete selection is the first in the
{
firstLi.addClass("selection")
++current
con.find("ul li").filter(function() {
return $(this).hasClass("selection");
}).next().addClass("selection").end().removeClass("selection")
return false;
}
}
}
}
AutocompleteActivities.init({
div: $("#options"),
})
})()

JQuery .focus() event changing DropDown option

I have a selectlist with that is built using jquery inside a grid. When a user enters a key the select list is built, I then call click() and focus() so that I can use the key commands again.
The problem that I have is that .focus() is changing the selection of the select list when fired when it is fired. Has anyone experienced this behaviour before or found a workaround? Thanks in advance
function INTEREST_createPaymentTypeDropDown() {
//Interest specific:
//build a dropdown for the enum
//if the PaymentType input exists
if ($("#PaymentType").length > 0) {
var cellPaymentTypeValue = $("#PaymentType").val();
var selectedOption;
$("#PaymentType").replaceWith("<select id='PaymentType' style='width:95px; height: 20px;' name='PaymentType'></select>");
$.each(INTEREST_PAYMENT_TYPES, function(key, val) {
var newoption = $("<option value=\"" + val + "\">" + key + "</option>");
if (val == cellPaymentTypeValue || key == cellPaymentTypeValue) {
//append select to the current value
selectedOption = val;
}
$("#PaymentType").append(newoption);
$("#PaymentType").addClass("t-input");
});
if (selectedOption != null) {
$("#PaymentType").val(selectedOption.toString());
}
}
function INTEREST_setEditField(field) {
if ($("#PaymentType").length > 0) {
// this is where the problem is
$("#PaymentType").click();
}
else {
$(".t-grid-content").find('.t-input').click();
$(".t-grid-content").find('.t-input').select();
}
INTEREST_persistPaymentTypeOnCellChange(field);
}
function INTEREST_persistPaymentTypeOnCellChange(field) {
//keep the value of the enum not the enum index
//in the payment type field
var paymentTypeCell = $(field).parent().children().eq(1);
if ($(paymentTypeCell).html().length == 1) {
$.each(INTEREST_PAYMENT_TYPES, function(key, val) {
if ($(paymentTypeCell).html() == val) {
$(paymentTypeCell).html(key);
}
});
}
}
$('td.t-grid-edit-cell', 'div#AccountPayments').live('keydown', function(event) {
if (event.which == 39 || event.which == 9) //Tab or right arrow
{
if ($(this).hasClass('t-last')) {
INTEREST_goToNextRow(this, event);
}
else {
INTEREST_goToRight(this, event);
}
}
else if (event.which == 37 || event.which == 9 && event.shiftKey) //left arrow. Todo: add shift tab
{
if ($(this).hasClass('t-first')) {
INTEREST_goToPreviousRow(this, event);
}
else {
INTEREST_goToLeft(this, event);
}
}
else if (event.which == 40) //down arrow
{
INTEREST_goDown(this, event);
}
else if (event.which == 38) //up arrow
{
INTEREST_goUp(this, event);
}
});
$("#PaymentType").live('click', function(event) {
$(this).focus();
});
Could it be that there's no empty option at the top of the list so that when the click() is called it's causing PaymentType to auto-select the 0th option?

Categories

Resources