jQuery - a little selector and code refactoring
This little tip should give an impression on how to refactor a small peace of jQuery code.
Imaging the following scenario. You want to click a button on a webpage and the click should disable all other click buttons on the page. Ok, easy going. But keep in mind there are some other button elements like input[type=button], input[type=reset], input[type=submit], button.
Let's start with the code:
$("#disableAll").on("click", function() {
//get all buttons, of any kind but the one that was clicked
var $buttons = $("input[type=button],input[type=reset],input[type=submit],button").not(this);
$buttons.attr("disabled",true);
});
The code is ok and works as it should. But we can do better than using a selector like this...
$("#disableAll").on("click", function() {
//get all buttons, of any kind but the one that was clicked
var $buttons = $(":submit,:reset,:button").not(this);
$buttons.attr("disabled",true);
});
The little change in the selector for the click button elements makes the code shorter an more elegant. But still we can do better... Let's chain the action of disabling to the selector
$("#disableAll").on("click", function() {
//get all buttons, of any kind but the one that was clicked
$(":submit,:reset,:button").not(this).attr("disabled",true);
});
It's an simple example but it demonstrates how your jQuery code can evolve in the right direction while developing.
HTH.
Written by Henning
Related protips
2 Responses
Lovely tip! but a quick question couldn't you give all the buttons you wanted to disable a class and then just call to that class instead of ":submit,:reset,:button". so then you wouldn't need not this because the disableAll button doesn't the class. Ex:
$("#disableAll").on("click", function () {
//get all buttons, of any kind but the one that was clicked
$(".off").attr("disabled", true);
});
Hi, thanks for the comment. This code snippet should only demonstrate the refactoring process with a little practical example. Your approach is totally right when having all the code in your hand. But when dealing with existing systems or only parts of the code, sometimes a neutral generic solution is necessary. But as mentioned before it's example code to demonstrate the process.