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 () {
        $(".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


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 15:03


1 Answers

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

jQuery('#op5').one("click" , function () {
          $(".white").addClass('white checked');
          $(".blue").addClass('blue checked');
          $(".sub_label :checked").addClass('sub_label')



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

Sudharsan S