JQuery shortcuts / class switching technique

Is there any other way to write this in jQuery?

Version 1

     $("#date_filter-enable").click(function() {

        $("#search_dates").removeClass("hidden");
     });

     $("#date_filter-disable").click(function() {

        $("#search_dates").addClass("hidden");
     });

Version 2

     $("input[id^=date_filter-]").click(function(e) {

        var clicked = $(e.target);
        var id = clicked.attr("id").split("-");
        var action = id[1];

        if(action == "enable")  
         $("#search_dates").removeClass("hidden");
        else
         $("#search_dates").addClass("hidden");
     });

I'm used to coding like this ... but I want to know if there is an efficient, readable, cool way to write it ... like switching, chaining ... best practices that I don't know ^ ^

I appreciate you sharing this! ^^

+5
source share
2 answers

You must use the method toggleClass.

$("input[id^=date_filter-]").click(function(e) {
     $("#search_dates").toggleClass("hidden");
 });
+4
source
$("input[id^=date_filter-]").click(function(e) {
        if($(this).attr("id").split("-")[1] == "enable")  
         $("#search_dates").removeClass("hidden");
        else
         $("#search_dates").addClass("hidden");
     });
0
source

All Articles