jquery keyup not firing - javascript

I use the following function on keyup event to redirect to another javascript function.
Problem is it does'nt seem to fire, although it does bind the function to the textbox.
$(document).ready(function () {
EnablePickTargetButton();
//clear contents; use a delay because tinyMCE editor isn't always fully loaded on document.ready
var t = setTimeout(function () {
if (typeof textEditorForCreate != 'undefined' && tinymce.editors.length > 0)
tinyMCE.activeEditor.setContent('');
}, 300);
var txtSearchUser = $('#txtSearchUser');
if(typeof txtSearchUser != 'undefined')
{
$('#txtSearchUser').keyup(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
searchUser();
}
else
alert('cucu');
});
}
});
Not even the alert shows up. Checking the html, I can see it doesn't add onkeyup to the textbox; The textbox is in a popup window hosted in a div on the form; But on document.ready it runs the function without error.

Try this delegate on document or closest static element. (If the element is added dynamically)
$(document).on('keyup','#txtSearchUser',function(){
//Code
});

it works :
$(document).ready(function(){
$('#txtSearchUser').keyup(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
else
alert('cucu');
});
});
http://jsfiddle.net/jMk5S/
check if you're referencing your html element properly. Perhaps you mix id with the class?

I edited your code and is working :
The problem is in your document ready function , you have a syntax error , next time check console in your browser to see what's wrong :
DEMO HERE
$(document).ready(function () {
//EnablePickTargetButton();
//clear contents; use a delay because tinyMCE editor isn't always fully loaded on document.ready
var t = setTimeout(function () {
if ($('#textEditorForCreate').length != 0 && tinymce.editors.length > 0)
tinyMCE.activeEditor.setContent('');
}, 300);
if($('#txtSearchUser').length!=0)
{
$('#txtSearchUser').keyup(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
searchUser();
}
else
alert('cucu');
});
}
});

Related

keyboard shortcut using javascript not working

I am using command + h as a shortcut key in my website. It is not doing the function to be done. After I click something on the window only it works flawlessly. Here is my code..
window.onkeydown = function(event) {
if (event.keyCode == 72 && (event.metaKey == true)) {
//some function
}
}
Somebody try to rectify . I have included this code only after the dom gets loaded
window.onkeydown will only work if it is focused. So on body load you should set focus.
<body onload="setFocus()">
function setFocus(){
window.focus();
}
Working DEMO HERE
You could probably make it work with focusing the body on window load with document.body.focus() and attaching an event listener like this:
window.onload = function() {
document.body.focus();
document.addEventListener("keydown", keyDownFunction, false);
};
function keyDownFunction(event) {
if(event.keyCode == 72 && (event.metaKey == true)) {
alert("You hit the right keys.");
}
}

How to write a single Jquery function to trigger on document change and ready events

What I am trying to do is just to call this function once the document has loaded but also whenever some of the elements values are changed. I was wandering if there is a way to do this without writing the same piece of code twice, for document.ready() event and document.change().
$(document).on("change", "#holiday-editor input[name=StartDate],input[name=EndDate]", function() {
that.UpdateDays();
if ($("#holiday-editor input[name=StartDate]").val() == $("#holiday-editor input[name=EndDate]").val() && $("#holiday-editor input[name=StartDate]").val() + $("#holiday-editor input[name=EndDate]").val() != "") {
$("#IsHalfDay").show();
} else {
$("#IsHalfDay").hide();
$("input[name=HalfDay]").removeAttr("checked");
$("#amPM").hide();
$("#HalfDayAP").val("");
}
});
What I basically need is this function to run and check already existing values on the form before they get changed.
Use like this:
var changeFn = function() {
that.UpdateDays();
if ($("#holiday-editor input[name=StartDate]").val() == $("#holiday-editor input[name=EndDate]").val() && $("#holiday-editor input[name=StartDate]").val() + $("#holiday-editor input[name=EndDate]").val() != "") {
$("#IsHalfDay").show();
} else {
$("#IsHalfDay").hide();
$("input[name=HalfDay]").removeAttr("checked");
$("#amPM").hide();
$("#HalfDayAP").val("");
}
};
$(document).on("change", "#holiday-editor input[name=StartDate],input[name=EndDate]", changeFn);
and you can call the changeFn() also on ready or whenever you want.

window.onbeforeunload only works after i refresh the page

note: i see this Question but the problem is not the same.
I have one page named login_check.cfm and this page do a location.href to home.cfm
inside the home.cfm i have this code
<script>
window.onbeforeunload = function() { window.history.go(0); };
</script>
or
<script>
window.onbeforeunload = function() { window.history.forward(1); };
</script>
my intention is to prohibit the User to use the back button, and its work, but only a do a refresh or use a link to do refresh.
the problem is my page is 90% ajax based and the most off the user go back to login page when they clicked backbutton.
use Document ready() make no difference.
suggestions ?
i found this old Question where rohit416 give a good answer and it still works
(function ($, global) {
var _hash = "!",
noBackPlease = function () {
global.location.href += "#";
setTimeout(function () {
global.location.href += "!";
}, 50);
};
global.setInterval(function () {
if (global.location.hash != _hash) {
global.location.hash = _hash;
}
}, 100);
global.onload = function () {
noBackPlease();
// disables backspace on page except on input fields and textarea.
$(document.body).keydown(function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which == 8 && elm !== 'input' && elm !== 'textarea') {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
});
}
})(jQuery, window);

JS: How to detect whether cursor is in textfield

I want to use some letters ( keys ) as shortcut for some actions in javascript. I want to check whether the cursor is focused on any textfield, form input, etc. so that the shortcut action will be canceled when user is typing something in a form or textfield.
For example, i want an alert() to be executed when user presses 'A'. But if the user is typing some text in a textarea like 'A website' then he will be pressing 'A', this time alert() should not be executed.
$(document).keydown( function( e ) {
if( e.target.nodeName == "INPUT" || e.target.nodeName == "TEXTAREA" ) return;
if( e.target.isContentEditable ) return;
// Do stuff
}
window.onkeydown = function(e){
if ( e.target.nodeName == 'INPUT' ) return;
handle_shortcut();
};
jQuery
$(window).bind('keydown',function(e){
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
alert('a');
});
or pure js
window.onkeydown = function(e){
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
alert('a');
};
What you can do in addition to this is define an array of non-alert element types, so input, textarea etc and then check none of those elements are currently the target.
Demo: http://jsfiddle.net/7F3JH/
You can bind and unbind the shortcut events depending on which element currently has focus on your page.
JavaScript
window.onload = initWindow();
function initWindow () {
attachShortcutHandler();
var inputs = document.getElementsByTagName('input');
for (var i = 0, max = inputs.length; i < max; i++) {
inputs[i].onfocus = removeShortcutHandler;
intputs[i].onblur = attachShortcutHandler;
}
}
function removeShortcutHandler () {
window.onkeypress = null;
}
function attachShortcutHandler() {
window.onkeypress = function () {
//your code here
}
}
jQuery
$(function () {
initShortcutHandler();
$('input, [any other element you want]')
.on('focus', function () {
$('body').off('keypress');
})
.on('blur', function () {
initShortcutHandler();
});
});
function initShortcutHandler() {
$('body').on('keypress', function () {
//do your stuff
});
}
jQuery mouseover()
$('element').mouseover(function() {
alert('over');
});
you need to make a flag as global. and set it false when any textbox has focus.
var flag = true;
$('input:type="text").focus(function(txt) {
flag= false; });
if(flag) //shortcut keys works...
Better use the focusOut method defined in JQuery. As per my understanding you can do something like this
$("input").focusout(function() {
if($(this).val() == "A"{
alert("your message");
return false;
}else{
//do other processing here.
}
});
Hope this helps :)

jQuery Crashes on .live("keyup")

I have some code here:
$(document).ready(function() {
$("#querybox").live("keyup", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$("#querybox").blur();
}
else {
search(document.getElementById('querybox').value);
}
/*if (document.getElementById('querybox').value == "") {
$("center").removeHighlight();
}*/
});
});
that detects a keyUp and uses it to search something. The problem is: when the #querybox is backspaced to the point where it is empty, the entire page crashes and I get the "Awwww, Snap!" message from Google Chrome.
I am using jQuery v1.7.2
Thx a million!
EDIT
I should also point out that the search() function highlights text in the body (notice the commented section). I am using the highlight plugin...
Search Fn:
function search(query) {
$("center").removeHighlight();
$(".paragraph").highlight(query);
$(".highlight").each(function (index) {
$(this).attr("id", "tmpforgoToByClassScrollhighlight" + index);
});
}
Try using .on(...) instead:
$("#querybox").on("keyup", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var queryBox = this;
if (code === 13) { // PRESSED ENTER
queryBox.blur();
}
else {
search(queryBox.val());
}
});
After your update:
You might want to look better into how you do your search functiom.
Cache some of those jQuery elements so you do not keep selecting them over and over on each keyup.
Also, I am not going through all of the .highlight code, but there probably is a bug in there that does not allow for an empty string, and that is why the website is causing the browser to crash.
You should use .delegate() instead
$(document).ready(function() {
//It will be a good advice to replace body with a parent element of #querybox
$("body").delegate("#querybox","keyup", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$("#querybox").blur();
}
else {
search(document.getElementById('querybox').value);
}
/*if (document.getElementById('querybox').value == "") {
$("center").removeHighlight();
}*/
});
});

Categories