Reputation: 5968
I'm trying to find a solution to make this code cleaner:
$(document).keypress(function(ev){
if($("#dialog").is(':visible') === false && $("#alertDialog").is(':visible') === false){
if(ev.keyCode=='13' && !$('#resetBtn').is(':focus') && !$('.edit-new').is(':focus') && !$('.edit-trash').is(':focus')){
return validateForm('valueTable');
}
if(ev.keyCode=='27'){
$('#resetBtn').click();
}
}
});
As you can see, I'm checking to see if three seperate inputs are not in foucs before exectuing my event. Is there a way to target #resetBtn, .edit-new, .edit-trash into one, nicely packed selector?
Upvotes: 2
Views: 600
Reputation: 268344
You could use single selectors and simply check the length of their returned elements. No reason to explicitly check for equality with false
when we can check the length property instead:
// Handle the keypress event on the document object
$(document).on("keypress", function (event) {
// Proceed if no visible dialogs
if (!$("#dialog:visible, #alertDialog:visible").length) {
// Checking which key was pressed
switch (event.which) {
case 13:
// If no focus is on #resetBtn, .edit-new, or .edit-trash
if (!$("#resetBtn:focus, .edit-new:focus, .edit-trash:focus").length) {
return validateForm("valueTable");
}
break;
case 27:
// Trigger the click event on #resetBtn
$("#resetBtn").trigger("click");
}
}
});
Upvotes: 1
Reputation: 3602
Would this do what you want?
$('#resetBtn:focus, .edit-new:focus, .edit-trash:focus').length === 0
You could use a similar statement for your visibility checks too.
Upvotes: 3