Keypress check not working [duplicate] - javascript

This question already has an answer here:
Click event not working for dynamically added Li->span->id
(1 answer)
Closed 6 years ago.
If i add the search bar right away, it works, the console returns the value of the search field every time i press enter, but if i add the search bar after the image was clicked it doesn't work.
http://codepen.io/Nadaga/pen/QEVaGA
$('#glass-image').on('click', function() {
$('#main').html('<input id="search-field" type="text" placeholder="Search"></input>');
})
$('#search-field').keypress(function (e) {
if (e.which == 13) {
console.log($('#search-field').val());
return false;
}
});

Since, the search-field is dynamically created, It has to be added like this (on the $document),
$(document).on('keypress', '#search-field' ,function(e) {
if (e.which == 13) {
console.log($('#search-field').val());
return false;
}
});

$('#glass-image').on('click', function() {
$('#main').html('<input id="search-field" type="text" placeholder="Search"></input>');
$('#search-field').keypress(function(e) {
if (e.which == 13) {
console.log($('#search-field').val());
return false;
}
});
})
Click event only works if the element already exist in html code. So the click event doesn't fire.It won't consider the new element which is created dynamically after the page loaded. Dynamic elements are created with the help of javascript or jquery(not in html).
source: https://stackoverflow.com/a/29674985/1848140

Related

How to combine keypress and onclick function Javascript? [duplicate]

This question already has answers here:
How to combine keypress & on click function in JavaScript?
(5 answers)
Closed 5 years ago.
I have the following two functions:
$("input").keypress(function(event) {
if (event.which == 13) {
//code
}
});
$('#login_submit').click(function () {
//code
});
The code which is being used in the functions are EXACTLY the same code, basically code duplication. So i was wondering if there is a way to combine these functions with an AND statement?? There is an question on Stack but it aks for an OR logic. If you want the OR solution here
EDIT: I am trying to make somthing like an explorer. Now I want to hold "shift" and click on an "input" to mark them all. So i need the "onclick" on my input element to be true AND my keydown to be true.
After your edit, I believe what you are looking for is something like the following.
var shift_hold = false;
$(document).keydown(function(e) {
if(e.which === 16) {
shift_hold = true;
}
})
$(document).keyup(function(e) {
if(e.which === 16) {
shift_hold = false();
}
})
$('input').click(function() {
if(shift_hold) {
//your code here
}
})
I want to hold "shift" and click on an "input" to mark them all. So I need the "onclick" on my input element to be true AND my keydown to be true.
Within the click event, you can check if a key is also pressed down (click and key-is-down).
You can use the event object to see which keys are pressed. shift/control/alt have their own explicit properties.
Example:
$("input").click(function() {
console.log(event.shiftKey)
if (event.shiftKey) {
$(this).addClass("selected")
} else {
$(this).removeClass("selected")
}
// could use .toggleClass("selected", event.shiftKey) here,
// shown expanded for clarity
});
.selected {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Shift-click input to select, click to unselect
<input type='text'>
<input type='text'>

double click is not working after 1st time

I have a MVC site and I have a html table and on double click on a cell it will go to edit mode and for the first time it works and next time when I double on the same cell or any other cell it dosen't work, when I make a click anywhere and then if I do double click it works fine.
I suspect some conflict between single click and double click.
$('#TableOverride tr:gt(0)').each(function () {
$(this).find('td:eq(9)').dblclick(function () {
EditCell(this, 9);
});
});
Update : Tested in Chrome and it works fine without any issues, it looks like a browser issue with IE 11 and earlier versions.
function EditCell(thisCell, colNum) {
var Id;
// if the table cell is not in edit mode
if ($(thisCell).find('input').length == 0) {
if (colNum == 4 && $(thisCell).parent().parent().parent()[0].id == 'OverrideTable') {
myBlk = $(thisCell).html();
$(thisCell).html('<input type="text" data-oldvalue="' + myBlk + '" />');
$(thisCell).find('input').val(myBlk);
$(thisCell).find('input').trigger('focus');
$(thisCell).find('input').keypress(function (e) {
if (e.which == 13) {
// If Enter key is pressed, update data.
myBlk = $(this).val();
if (myBlk == '') {
$('div.errorSummary').html('my block cannot be empty!');
$('div.errorSummary').show();
} else {
Loadmyblk(myBlk, this);
LeaseOverrideObj.GetLeaseOverride());
}
});
}
Try this, it should work, add custom class e.g. "EditableCell" for using in dblclick event binding on document.
$('#TableOverride tr:gt(0)').each(
function () {
$(this).find('td:eq(9)').removeClass('EditableCell').addClass('EditableCell');
});
});
$(document).on('dblclick', '.EditableCell', function()
{ EditCell(this, 9);
});
Please note $(document).on should not be called in any loop, it should be called only once in document.ready.
Js Fiddle
Updated fiddle link to demo dblclick on dynamically added events

Key press dont work on dynamicly created element [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
i am trying to add a new span of tag inside tags div.
my problem is that the code under span[id="newtag"] doesnt
work. how can i make this code work?
$(document).ready(function () {
$('#tags').on("click", function () {
$(this).append('<span id="newtag" contenteditable="true"></span>');
$(this).children(":last").focus();
});
$('span[id="newtag"]').keypress(function (k) {
if (k.which == 13 || k.which == 32) {
$(this).append('gfskjsokdfla');
}
});
});
Use event delegation for created dymanically dom elements.
$('#tags').on('keypress', 'span[id="newtag"]', function(k){
if (k.which == 13 || k.which == 32) {
$(this).append('gfskjsokdfla');
}
});

preventing javascript keyup function effect when the user is in a text box?

Currently I use the following code to allow the user to "flip through" content on my web app:
$(this).keyup(function(e) {
if(e.which == 37) {
document.location = $("#prev_button").attr('href');
}else if(e.which == 39) {
document.location = $("#next_button").attr('href');
}
});
The problem is that if the user is in the search form at the top of the page, I do not want the arrow keys to redirect the page (instead they should act as they normally would without the functionality, i.e. allow the text cursor to move around the text).
the form id is "searchForm" - can I add a clause to the the if statement which evaluates to false if the search form is selected?
You can stop the propagation of the event when in the textbox so the event doesn't make it to your other handler:
$('#searchbox').keyup(function(e) {
e.stopPropagation();
});
I would use something like: Demo
$(this).keyup(function(e) {
if(~['input', 'textarea'].indexOf(e.target.tagName.toLowerCase())) return;
if(e.which == 37) {
document.location = $("#prev_button").attr('href');
}else if(e.which == 39) {
document.location = $("#next_button").attr('href');
}
});
This way you can exclude all <input> and <textarea> elements.
IMO, excluding just #searchbox isn't a great solution because in the future you may change its id or include other text fields, but forget you must reflect changes in the exclusion script.
Check out this thread :)
Find if a textbox is currently selected
function checkFocus() {
if ($(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea") {
//Something's selected
return true;
}
}

How to open popover with keyboard shortcut? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Keyboard shortcuts with jQuery
I want to display a popover window using a shortcut key instead of clicking the icon on the toolbar.
Do you have any good idea?
Thank you for your help.
Abody97's answer tells you how to determine if a certain key combo has been pressed. If you're not sure how to get that key combo to show the popover, this is what you need. Unfortunately, Safari makes this needlessly complicated.
In the global script, you'll need a function like the following to show a popover, given its ID and the ID of the toolbar item that should show it:
function showPopover(toolbarItemId, popoverId) {
var toolbarItem = safari.extension.toolbarItems.filter(function (button) {
return button.identifier == toolbarItemId && button.browserWindow == safari.application.activeBrowserWindow;
})[0];
var popover = safari.extension.popovers.filter(function (popover) {
return popover.identifier == popoverId;
})[0];
toolbarItem.popover = popover;
toolbarItem.showPopover();
}
You'll also need code to call this function in your global script's message listener, like the following (this sample does not assume you already have a message listener in place):
safari.application.addEventListener('message', function (e) {
if (e.name == 'Show Popover') {
showPopover(e.message.toolbarItemId, e.message.popoverId);
}
}, false);
Finally, in your injected script, the function that listens for the key combo needs to call dispatchMessage, as below:
safari.self.tab.dispatchMessage('Show Popover', {
toolbarItemId : 'my_pretty_toolbar_item',
popoverId : 'my_pretty_popover'
});
(Stick that in place of showPopUp() in Abody97's code sample.)
Note: If you only have one toolbar item and one popover (and never plan to add more), then it becomes much simpler. Assuming you've already assigned the popover to the toolbar item in Extension Builder, you can just use
safari.extension.toolbarItems[0].showPopover();
in place of the call to showPopover in the global message listener, and omit the message value in the call to dispatchMessage in the injected script.
Assuming your shortcut is Ctrl + H for instance, this should do:
var ctrlDown = false;
$(document).keydown(function(e) {
if(e.keyCode == 17) ctrlDown = true;
}).keyup(function(e) {
if(e.keyCode == 17) ctrlDown = false;
});
$(document).keydown(function(e) {
if(ctrlDown && e.keyCode == 72) showPopUp(); //72 is for h
});
Here's a reference for JavaScript keyCodes: little link.
Here's a little demo: little link. (It uses Ctrl + M to avoid browser-hotkey conflicts).
I believe this could help you: http://api.jquery.com/keypress/
In the following example, you check if "return/enter" is pressed (which has the number 13).
$("#whatever").keypress(function(event) {
if( event.which == 13 ) {
alert("Return key was pressed!");
}
});

Categories