JQuery Toggle Script

I have a page with different tables showing the values ​​in centimeters and inches. Initially my tables are filled with inches

There is a button that you can click, and then it will change the table to show values ​​in centimeter

As you can see how my code works, each table will have its own button for changing inches to cm and vice versa.

What I'm looking for is a click on one of the buttons that will change all values ​​for all tables. If someone clicked the button located in table 2 to see centimeters, change all the tables to centimeters. The button is embedded in each of the 4 DIVs containing my tables. would you do it

<a class="unitpicker on" href="#"></a> 

jQuery(document).ready(function(e) {
    jQuery('#Laura .unitpicker').click(function(e) {
    e.preventDefault();
    jQuery(this).toggleClass('on');
    jQuery('#Laura .imperial').toggle();
    jQuery('#Laura .metric').toggle();
});

jQuery('#Petites .unitpicker').click(function(e) {
    e.preventDefault();
    jQuery(this).toggleClass('on');
    jQuery('#Petites .metric').toggle();
    jQuery('#Petites .imperial').toggle();
});

jQuery('#Plus .unitpicker').click(function(e) {
    e.preventDefault();
    jQuery(this).toggleClass('on');
    jQuery('#Plus .metric').toggle();
    jQuery('#Plus .imperial').toggle();
});

jQuery('#PlusPetites .unitpicker').click(function(e) {
    e.preventDefault();
    jQuery(this).toggleClass('on');
    jQuery('#PlusPetites .metric').toggle();
    jQuery('#PlusPetites .imperial').toggle();
});
+3
source share
2 answers

JSBIN DEMO

jQuery(function( $ ){ // DOM ready and secured $ alias

    // Collect every button with class .unitpicker
    var $unitBtns = $('.unitpicker');

    $unitBtns.click(function(e) {
        e.preventDefault();
        $unitBtns.toggleClass('on');      // toggle class on every button
        $('.imperial, .metric').toggle(); // swap names
    });

});
0
source

Start by grouping the click function code:

jQuery(document).ready(function(e) {
    jQuery('.unitpicker').click(function(e) {
        e.preventDefault();
        jQuery(this).toggleClass('on');
        jQuery('#'+this.id+' .metric').toggle();
        jQuery('#'+this.id+' .imperial').toggle();
    });
});
-1
source

All Articles