How to stop toggleClass () when a button is clicked?

There are 4 divs on my page and button. If you click on the div, it will switch to Class.

At the click of a button, I want all the selected areas to be selected to remain selected, but I don’t want to divs toggleClass anymore after clicking the button.

Is there any way to do this?

My code is as follows:

function submit() {
//this is the function I do not know how to define
};

function choose() {
    $('.options').click(function() {
        $(this).toggleClass('highlighted');
    });
    return;
};

$(document).ready(function() {
    $('body').append('<div class="options">option1</div>');
    $('body').append('<div class="options">option2</div>');
    $('body').append('<div class="options">option3</div>');
    $('body').append('<div class="options">option4</div>');
    $('body').append('<button onclick=submit()>Submit</button>');
    choose();
});

I was looking for a way to stop the select () function. Creating the goOn variable and changing its value to false when clicking the button plus a bit of code below did not help.

var goOn = true;
while (goOn) {
    choose();
};
+3
source share
5 answers

Cancel the click event with .off():

function submit() {
    $('.options').off('click')
};

JsFiddle example

+3
source

. , , . .

 $('.options').one( "click", function() {
        $(this).toggleClass('highlighted');
    });
0

You can unbind an event listener (this is compatible with older and latest versions of jQuery):

function choose() {
    $('.options').click(function () {
        $(this).toggleClass('highlighted');
    });
    return;
};
choose();
$('button').click(function () {
    $('.options').unbind('click');
});

Fiddle

0
source
function choose() {
$('.options').click(function() {
    $(this).toggleClass('highlighted');
    if ($('.options').length == $('.highlighted').length)
    {
      $('.options').off('click');
    }
});
return;};

http://jsfiddle.net/G7mb3/2/

0
source

Logical, complete example:

jsFiddle Demo

JavaScript / jQuery:

$(document).ready(function() {

ok2toggle = 1;

$('body').append('<div class="options">option1</div>');
$('body').append('<div class="options">option2</div>');
$('body').append('<div class="options">option3</div>');
$('body').append('<div class="options">option4</div>');
$('body').append('<button id="mySubmit">Submit</button>');

choose();

function choose() {
    $('.options').click(function() {
        if (ok2toggle==1)
            $(this).toggleClass('highlighted');
    });
    return;
};

$('#mySubmit').click(function() {
    ok2toggle = 0;
});

}); //END document.ready

OR, replace submit Sub with this to use the Submit button as a switch:

Revised jsFiddle :

$('#mySubmit').click(function() {
    ok2toggle = !ok2toggle;
});

Please note that the id has been added to your submit button, and inline javascript (has never been a good idea) has been removed.

0
source

All Articles