Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Radio Button Running Multiple Times

Sorry, kinda new to jQuery been doing some reading but been unable to find a solution.

I have a radio button that on click runs some jQuery:

<input type="radio" id="op5" value="1" name="options2" class="custom" />

On clicking this radio button the following jQuery runs to do multiple things on the page

    jQuery('#op5').click(function () {
        $('input[type=checkbox]').trigger('click');
        $(".white").attr('class', 'white checked');
        $(".blue").attr('class', 'blue checked');
        $(".sub_label").attr('class', 'sub_label')
        $(".sub_label checked").attr('class', 'sub_label')

    });

At the moment if the user re-clicks the radio button it re runs and will uncheck the checkboxes as it re runs the line

$('input[type=checkbox]').trigger('click');

Is there a way I can stop the code in my jQuery function running for a second time?

JS Fiddle - https://jsfiddle.net/jqh3L8t6/

like image 200
Legend1989 Avatar asked Mar 17 '23 08:03

Legend1989


1 Answers

Use .one() in jquery it triggers only one time. Use .addClass() instead of add attr() for class

jQuery('#op5').one("click" , function () {
          $('input[type=checkbox]').trigger('click');
          $(".white").addClass('white checked');
          $(".blue").addClass('blue checked');
          $(".sub_label :checked").addClass('sub_label')

 });

Fiddle

like image 90
Sudharsan S Avatar answered Mar 28 '23 01:03

Sudharsan S