javascript function is not executing - javascript

I have a checkbox. If I checks it, it will select all results:
HTML:
<input type="checkbox" id="selectallcheckbox" onClick="toggle(this)" />
And Javascript:
function toggle(source = false) {
if(!source)
{
var source = document.getElementById('selectallcheckbox');
}
checkboxes = document.getElementsByName('id[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
var id = checkboxes[i].id;
var res = id.replace("checkbox", "tr");
if(source.checked)
{
$('#' + res + '').addClass('selected');
} else {
$('#' + res + '').removeClass('selected');
}
}
}
Now I am trying to select all results if I click CTRL+A on my keyboard. Here is my JavaScript:
jQuery(document).keydown(function(e) {
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
e.preventDefault();
toggle();
}
}
});
But this function is not works. How can I make ctrl + a to select all results

The toggle function requires an argument or nothing. When no argument is passed the argument itself can be got directly from the dom. In the html the toggle function get the this keyword. The element itself is passed. But if no argument is passed the argument is undefined and so it can be computed dynamically:
<input type="checkbox" id="selectallcheckbox" onClick="toggle(this)"/>
In the toggle function try to change from:
function toggle(source = false) {
if(!source)
{
var source = document.getElementById('selectallcheckbox');
}
...........
to:
function toggle(source) {
if (source === undefined) {
source = document.getElementById('selectallcheckbox');
}
and, finally, in your jQuery(document).keydown(function(e) { change to:
jQuery(document).keydown(function(e) {
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
e.preventDefault();
// get the argument to the toggle function
var eleObj = document.getElementById('selectallcheckbox');
// toggle the checkbox status
eleObj.checked = !eleObj.checked;
// call the toggle function with the correct argument
toggle(eleObj);
}
}
});

I found solution:
jQuery(document).keydown(function(e) {
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
e.preventDefault();
document.getElementById("selectallcheckbox").click();
}
}
});

Related

e is undefined, correct syntax for a recursive handler function

How to make a correct recursive call? In this code the console says me "e is undefined".
It's a event listener for a button ul in a unordered list.
This is my code:
$("button#ul").on("click", function(event){
var button = $(this);
$(button).toggleClass("active");
if ($(button).hasClass('active')){
//event listener
$(document).on("keydown", **checkExit** = function(e) {
if (exit(e) == true){
$(button).removeClass('active');
$(this).off("keydown");
}
**checkExit();**
});
function exit(event){
// alert("prevKeyCode: "+prevKeyCode);
var code = event.keyCode || event.which;
var doubleEnter = (code == 13 && prevKeyCode == code);
if (event.type == "click"){
return true;
}
else if (event.type == 'keydown'){
if (code == 27 || doubleEnter) {
prevKeyCode = null;
return true;
}
else if (code == 13) {
prevKeyCode = 13;
}
else {
prevKeyCode = code;
}
return false;
}
}
I think I should define outside the function checkExit...
You need to pass the event as a parameter when calling checkExit again:
$(document).on("keydown", checkExit = function(e) {
if (exit(e) == true) {
$('button').removeClass('active');
$(this).off("keydown"); //spegne il gestore corrente
}
checkExit(e);
});

three button keyCode hotkey javascript

From another stackoverflow post (How can I add a JavaScript keyboard shortcut to an existing JavaScript Function?) I have this hotkey code:
function doc_keyPress(e) {
if (e.shiftKey && e.keyCode == 80) {
//do something
}
}
document.addEventListener('keyup', doc_keyPress, false);
which works with two keys. But with three keys, shift + l + m for example, it does not work.
the if statement would be:
if (e.shiftKey && e.keyCode == 76 && e.keyCode == 77) {}
again this does not work.
How do I get this working for shift + l + m.
tricky, tricky, but I managed to get it working. Just be aware that browsers have their own hot keys (like chromes [ctrl]+[shift]+i) which may override the function.
<!DOCTYPE html>
<html>
<body>
<input id="myInput" onkeydown="keyDownEvent(event)" onkeyup="resetKeys()">
</body>
</html>
<script>
var key1Pressed=false;
var key2Pressed=false;
function resetKeys(){
key1Pressed=false;
key2Pressed=false;
}
function keyDownEvent(e){
e=e||event, chrCode=(typeof e.which=="number")?e.which:e.keyCode;
if (e.shiftKey && chrCode === 76) key1Pressed=true;
if (e.shiftKey && chrCode === 77) key2Pressed=true;
if(key1Pressed && key2Pressed){
alert('Three Keys Are Pressed');
key1Pressed=false;
key2Pressed=false;
}
}
document.getElementById('myInput').focus();
</script>
Using a closure, I would envisage you can do something like this
var doc_keypress = (function() {
var prevWasL = false;
return function(e) {
if (e.type == 'keypress') {
if (e.shiftKey && !(e.ctrlKey || e.metaKey)) {
if (prevWasL) {
if (e.charCode == 77) {
console.log('doing it');
prevWasL = false;
return;
}
}
if (e.charCode == 76) {
prevWasL = true;
return;
}
}
prevWasL = false;
} else { // keyup
if (e.key == 'Shift') {
prevWasL = false;
}
}
}
}());
document.addEventListener('keypress', doc_keypress);
document.addEventListener('keyup', doc_keypress);
Add both keypress AND keyup event listeners so that the scenario of
Shift + L, release both, Shift + M, doesn't trigger a false positive
This would require shift then L then M being pressed in that order ... if you want either order of L and M, then the code would be a little different, but you should be able to figure that out
NOTE: I use charCode, because firefox at least, keyCode is always 0 on keyPress event
If you're trying to double press or triple press keys and catch an event after this, I've written a simple helper:
function KeyPress(_opts) {
this.opts = Object.assign({}, {
counts: {},
timeouts: {},
timeBetweenPresses: 300
}, _opts || {});
}
KeyPress.prototype.bubbledReset = function bubbledReset(keyCode) {
var self = this;
if (this.opts.timeouts[keyCode]) {
clearTimeout(this.opts.timeouts[keyCode]);
this.opts.timeouts[keyCode] = 0;
}
this.opts.timeouts[keyCode] = setTimeout(function () {
self.opts.counts[keyCode] = 0;
}, this.opts.timeBetweenPresses);
};
KeyPress.prototype.onTap = function onTap(cb) {
var self = this;
return function handler(event) {
self.opts.counts[event.keyCode] = self.opts.counts[event.keyCode] || 0;
self.opts.counts[event.keyCode]++;
self.bubbledReset(event.keyCode);
cb(event.keyCode, self.opts.counts[event.keyCode]);
};
};
Usage
Simply use the onTap method to instance:
var keyPress = new KeyPress();
document.addEventListener('keyup', keyPress.onTap(function (keyCode, count) {
if (keyCode === 68 && count === 3) {
// 68 was tapped 3 times (D key)
}
if (keyCode === 13 && count === 6) {
// 13 was tapped 6 times (ENTER key)
}
}));
Hope this helps someone else!
Or if you prefer es6:
class KeyPress {
constructor(_opts) {
this.opts = Object.assign({}, {
counts: {},
timeouts: {},
timeBetweenPresses: 300
}, _opts || {});
}
bubbledReset(keyCode) {
if (this.timeouts[keyCode]) {
clearTimeout(this.timeouts[keyCode]);
this.timeouts[keyCode] = 0;
}
this.timeouts[keyCode] = setTimeout(() => {
this.counts[keyCode] = 0;
}, this.timeBetweenPresses);
}
onTap(cb) {
return event => {
this.counts[event.keyCode] = this.counts[event.keyCode] || 0;
this.counts[event.keyCode]++;
this.bubbledReset(event.keyCode);
cb(event.keyCode, this.counts[event.keyCode]);
};
}
}

Call function based on input

I've an textbox in asp.net,when i enter ";" semicolon in textbox means it have to call a function.Is there any way to do this.please help me out guys..i tried change function but it calls at every keypress in textbox.
$('#prgrp').on('change', function (evt)
{
var txt = $("#prgrp").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
var duplicateValues = [];
for (var i = 0; i < valueSortArray.length; i++)
{
if (valueSortArray[i + 1] == valueSortArray[i])
{
duplicateValues.push(valueSortArray[i]);
}
}
if (duplicateValues.length > 0)
{
$("#duplicate").html("Don't enter repeated values");
$('#duplicate').css('color', 'RED');
$("#prgrp").autocomplete("disable");
}
else {
$("#duplicate").html("");
$("#prgrp").autocomplete("enable");
}
});
Try this:-
$("#prgrp").keypress(function (e) {
if (e.keyCode == 59) {
//Call your function here
}
});
Please note, you can also use e.which in place of e.keyCode as it is jquery standardized.
Try this
$('#prgrp').bind('keypress', function(e) {
var code = e.keyCode || e.which;
if(code == 59) { //
//Do something
}
});
Demo
try this code
$( "#prgrp" ).keypress(function( event ) {
if ( event.which == 59 || event.keycode == 59 ) {
//your function call
}
});

Unable To get Selected text on Enter key press from list box

I am trying for smart search on my web page, so in my search on Click event I am getting Text which is selected in same textarea and but when I try with On keypress I'm unable to do find text of selected item. I am using jquery1.4.2 and tried option:select but still fail to do so...
My Code for click
$(document).ready(function() {
$('#ctl00_ContentPlaceHolder1_smartSearch').keyup(function(e) {
var str = document.getElementById('ctl00_ContentPlaceHolder1_smartSearch');
//alert("hi");
if (str.value.length >= 2) {
if (e.keyCode != 40 && e.keyCode != 38 && e.keyCode != 13) {
var str1 = str.value;
var str2 = str1.replace(' ', '+')
var url = "../SiteCache/90D/SmartGetQuoteData.aspx?Type=EQ&text=" + str2;
$("#ajax_response_smart").load(url);
}
$("#ajax_response_smart").show();
$('#listEQ li').live('click', function() {
var selected = $(this).text();
$("#ajax_response_smart").remove();
if (selected != "") {
var scripcode = selected.split("|");
document.getElementById('ctl00_ContentPlaceHolder1_smartSearch').value = scripcode[0];
document.getElementById('ctl00_ContentPlaceHolder1_hdnCode').value = scripcode[2];
}
});
var $listItems = $('#listEQ li');
var key = e.keyCode,
$selected = $listItems.filter('.ui-state-hover'),
$current;
if (key != 40 && key != 38 && key != 13)
{ return; }
else {
$listItems.removeClass('ui-state-hover');
}
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();
}
}
else if (key == 13) {
}
}
else {
$("#ajax_response_smart").hide();
}
if (typeof $current != "undefined") {
$current.addClass('ui-state-hover');
}
});
$("#ajax_response_smart").mouseover(function() {
var $listItems1 = $('#listEQ li');
$selected1 = $listItems1.filter('.ui-state-hover');
$(this).find("#listEQ li").mouseover(function() {
($selected1).removeClass("ui-state-hover");
$(this).addClass("ui-state-hover");
});
$(this).find("#listEQ li").mouseout(function() {
$(this).removeClass("ui-state-hover");
});
});
});
Please Suggest and Thanks in advance
hey i got my the answer i called the keypress event on my textbox in aspx page and from there i came on the currently paosted js page then on keypress event i got value.i.e not able to use keyup event to detect enter

How to limit Tab listener to callback only if the textbox has change

I'm trying to implement a Tab key listener for a textbox.
$('#mytextbox').live('keydown', function (e) {
if (e.keyCode == 9 || e.which == 9) {
// TO DO SOMETHING
}
});
However, for some reason I need to limit the tab listener's callback to invoke only when the textbox has changed. Is there anyway to do this?
You might be able to check the value of the input field to make sure it's different from it's original value?
E.g.
$('#mytextbox').live('keydown', function (e) {
if ((e.keyCode == 9 || e.which == 9) && ($('#TextBox').val() != 'Starting Value')) {
// TO DO SOMETHING
}
});
You can do it just like:
var data = "";
$('#mytextbox').live('keydown', function (e){
if(e.which == 9 || e.keyCode == 9){
if($(this).val() != data){
alert('changed!');
data = $(this).val();
}
}
});
http://jsfiddle.net/DDCZS/1/
Or without storing / knowing value of that textbox:
var changed = false;
$('#mytextbox').on('keydown', function (e) {
if (e.which == 9 && changed) {
e.preventDefault();
// TO DO SOMETHING
alert("works");
changed = false;
} else {
changed = true;
}
});
http://jsfiddle.net/9a37b/

Categories