I'm trying to turn a button-click into a toggle that enables or disables a function, depending on its state. The function allows the enter key to be used for a form submission.
var enterToggle = true;
function enterToggleListener(elem) {
enterKeyPress();
elem.click(function() {
enterToggle = !enterToggle;
console.log('enter-toggle clicked')
if (enterToggle === false) {
console.log('enter toggle false')
// What do I need to add here to stop 'enterKeyPress()'?
} else {
console.log('enter toggle true')
enterKeyPress();
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(e.which == 13){
$('#noteButton').click();
}
});
}
enterToggleListener($('#toggle-button'));
What I don't understand is how to stop the enterKeyPress() function when enterToggle is false. Any suggestions?
EDIT: Cleaned-up code, with #James Montagne's answer added
var enterToggle = true;
function enterToggleListener(elem) {
elem.click(function() {
enterToggle = !enterToggle;
if (enterToggle === false) {
$('#enter-toggle').text('Enter key saves note (OFF)')
} else {
$('#enter-toggle').text('Enter key saves note (ON)')
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
enterKeyPress();
enterToggleListener($('#enter-toggle'));
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
You can simply check the value of the variable within your handler. This way you don't need to keep adding and removing the handler as seems to be your current approach.
However, if you must add and remove for some reason, you would use off.
Related
Here is my code
document.onkeydown = function (a) {
if (a.which == 13) {
alert("Not Anymore");
}
}
document.onkeydown = function (b) {
if (b.which == 65) {
auto();
}
}
document.onkeydown = function (c) {
if (c.which == 83) {
auto2();
}
}
Only the last snippet works can someone explain why this is happening
check my website and you can see it isnt working when you press a but when you press b it is
Thanks, I appreciate the help and feedback
You're binding the same event on the document multiple times. So, the later event handlers override the previous event handlers just like the functions with same name does. You need to bind only one event handler and use if... else in it.
You can use this
document.onkeydown = function (e) {
if (e.which == 13) {
alert("Not Anymore");
} else if (e.which == 65) {
auto();
} else if (e.which == 83) {
auto2();
}
};
Also, use addEventListener instead of onkeydown.
document.addEventListener('keydown', function (a) {
if (a.which == 13) {}
...
}, false);
I’m using the following function to populate some combo boxes.
<script type="text/javascript">
function getcompany() {
$.post('filters.php',
$('form[name="report1"]').serialize(),
function (output) {
var options = output.split(',');
$('#M1').html(options[0]).show();
$('#T1').html(options[1]).show();
$('#I1').html(options[2]).show();
$('#C1').html(options[3]).show();
});
}
</script>
This is trigged by an OnChange event and works fine if a user only wants to filter by one item in the combo box. But if the Control or Shift key is used with the intention of selecting multiple items, the options change before selecting the next item. So, what I need is a way to detect if either of those keys are down, pause the function, then resume it after the key is released.
After another day trying things, I came up with this. Also added the shift key.
<script type="text/javascript">
//Set default variable to no
downkey = "No";
//Set variable to yes if key(s) are down
$(document).keydown(function(down){
if(down.keyCode == 16 || down.keyCode == 17) {
downkey = "Yes";
}
});
//Return variable to no and call the function when the key(s) are released
$(document).keyup(function(up){
if(up.keyCode == 16 || up.keyCode == 17) {
downkey = "No";
getcompany();
}
});
</script>
<script type="text/javascript">
function getcompany() {
if(downkey == "No"){//Checks the downkey variable to see if it is currently set to Yes or No
$.post('filters.php',
$('form[name="report1"]').serialize(),
function (output) {
var options = output.split(',');
$('#M1').html(options[0]).show();
$('#T1').html(options[1]).show();
$('#I1').html(options[2]).show();
$('#C1').html(options[3]).show();
});
}
}
</script>
I haven't tested this yet, but you can determine if the control key is pressed using the event object. e.ctrlKey
button.onclick = function (e) {
if (e.ctrlKey) {
// do nothing
}else {
getCompany();
}
}
The same goes for the shift key e.shiftKey
button.onclick = function (e) {
if (e.ctrlKey || e.shiftKey) {
// do nothing
}else {
getCompany();
}
}
I have a div listOfTodos that is empty by default. No white space inside the html. I also have a textbox that when enter is pressed it appends text to listOfTodos. For some reason is:empty doesn't work and it always says it's empty.
My code for checking is:
if ($('#listOfTodos').is(':empty')) {
console.log("empty");
} else {
console.log("not empty");
}
Then above this code I also have:
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>'); }
});
The label above is saved and is retrieved on every reload. What's going on?
Doesn't JS run code from top to bottom? I have the keypress above the if statement inside my js file.
Yes, but the event handler is not executed until the event is triggered, which is not possible until after the whole script executed.
I.e.
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>');
}
});
if (....) { }
will execute the if statement only once after the event handler was bound.
You have to put the if statement inside the handler if you want to run it after the event fired:
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>');
if ($('#listOfTodos').is(':empty')) {
console.log("empty");
} else {
console.log("not empty");
}
}
});
Or put it in a function if you want to run that logic in multiple places:
function isEmpty() {
if ($('#listOfTodos').is(':empty')) {
console.log("empty");
} else {
console.log("not empty");
}
}
// run on load
isEmpty();
$("#someTextbox").keypress(function(e) {
if (e.keyCode == 13) {
$('#listOfTodos').append('<label>Some text</label>');
// run on change
isEmpty();
}
});
Use
if ($.trim($('#listOfTodos').text()) == '') {
alert("empty");
} else {
alert("not empty");
}
Fiddle
I'd like to trigger an event once after key down and a different event only after the down arrow key has been released, like so:
$('body').keydown(function (e)
{
if(e.keyCode==40)
{
//do something
}
$('body').keyup(function (d)
{
if(d.keyCode==40)
{
//do something else
}
}
}
This code only functions partially. The keydown is triggered continuously as the down arrow key is held.
I have a setInterval whose refresh rate I'm altering when I hold the arrow key. Unforunately setTimeOut isn't an option in this situation.
So my code looks something like this:
clearInterval(interval);
refresh = 100;
interval();
$('body').keydown(function (e) {
if(e.keyCode==40) {
//do something
}
return false;
})
.keyup(function(e) {
if(e.keyCode==40) {
//do something else
}
return false;
});
$('body').on('keyup', function (e) {
if(e.keyCode==40) {
//do something
}
// after first keyup set to handle next keydown only once:
$(this).one('keydown', function(e) {
if(e.keyCode==40) {
//do something else
}
});
});
If you need exactly trigger the event and not handle as it's in your example, then you need to use $.trigger() method.
If you want to do some action only once while the key remains pressed, simply keep track of that:
var arrowKeyDown = false;
$('body').keydown(function(e) {
if (e.which == 40 && !arrowKeyDown) {
arrowKeyDown = true;
// ...
}
});
$('body').keyup(function(e) {
if (e.which == 40) {
arrowKeyDown = false;
}
});
Demo: http://jsfiddle.net/utfwQ/
$('body').keydown(function (e)
{
console.log('down');
}).keyup(function(e){console.log('up')});
If you really need to remove the keyup listener when you're done,
http://jsfiddle.net/CgmCT/
document.body.addEventListener('keydown', function (e) {
if(e.keyCode === 40){
console.log('key 40 down');
// key down code
document.body.addEventListener('keyup', function listener(d){
if(d.keyCode === 40){
document.body.removeEventListener('keyup', listener, true);
console.log('key 40 up');
// key up code
}
}, true);
}
}, true);
I have a input on page in some div:
<input style='border:1px solid black;' type='text' id='inputFindBy_Name' />
and o jquery javascript function monitored it:
$("div[id=mainGridPage] input").bind("keyup", function (event) {
if (event.keyCode == 13) {
var searchField = "Name";
var searchValue = $(this)[0].value;
var pageIndex = "1";
var sortField = "Name";
Application.Services.ProductTypeService.LoadMainGridProductType(pageIndex, sort, sortField, searchField, searchValue, ResultLoadMainGridProductType, ErrorLoadMainGridProductType);
}
});
when user typed something and pressed ENTER (event.keyCode == 13) I need do some thing but without reloading the page. How do that?
Try this one
$("div[id=mainGridPage] input").bind("keyup", function (event) {
if (event.keyCode == 13) {
// needed do something here without reloading the page
return false;
}
});
just like a link.
Just return false from within the function:
var code = event.keyCode || event.which;
if (code == 13) {
// do what you have to do.....
return false;
}
Edit: the keyup event is triggered "too late" after the form submission event was already dispatched - you can't cancel or stop it in that stage. So, handle the keypress event instead. Change the line to:
$("div[id=mainGridPage] input").bind("keypress", function (event) {
And the return false; will indeed stop the form from submitting.
Live test case.
You need to do a event.stopPropagation() and maybe the return false;. Please use event.which because event.keyCode is not compatible with all browsers, also you are using div[id=mainGridPage] input which searches for an ID, a better way to put this down is: div#mainGridPage input, and probably faster.
$("div#mainGridPage input").bind("keyup", function (event) {
if (event.which == 13) {
event.stopPropagation();
// needed do something here without reloading the page
return false.
}
});
try this. this will work i think:
$("div[id=mainGridPage] input").keypress(function(event) {
if (event.keyCode == 13) {
// do your code
console.log('hello');
return false;
}
});