Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the CURRENT value of a checkbox onclick

From what I can tell from reading everything I can find here, this doesn't seem to be possible, but I just thought I'd ask.

What I want to do is prevent a checkbox from doing its default toggle action and run a function instead. This function needs to know the checkboxes CURRENT state- as opposed to the state it will be in after the click event has toggled it- and that toggle needs to be prevented.

So say I have this input for example

<input type="checkbox" onclick="setDefault(this);return false;" />

And the setdefault function is something like this

function setDefault(el) {
    if(jQuery(el).is(':checked'))
        {
        alert('Turning current default off- setting default to Home settings');
        jQuery(el).prop('checked',false);
        return; 
        }
    else
        {
        alert('setting a new default');
        jQuery(el).prop('checked',false);
        return; 
        }
}

When that runs it gets the status the checkbox has been changed to, whreas what I need it to do is prevent the status from changing, find out its current status and then decide what to do.

I have tried every combination of preventDefault() and return false I can think of both in the function and the onclick event and have tried using the onchange event etc etc, but nothing seems to allow me to call a function that fires when the checkbox is clicked that allows the function to get the current value of the checkbox before it is changed by the click event.

Probably I just need to rethink this but if there is anything obvious I have missed I'd be most grateful

like image 346
David O'Sullivan Avatar asked Nov 04 '22 10:11

David O'Sullivan


1 Answers

Since the change happened already, the state of the checkbox is the opposite of what it is now. That solves your first problem.

To reset the state, just set the checkbox's checked value to what it isn't now, which is what it was before.

(my, this sounds like something the Mad Hatter would say!)

like image 140
cdeszaq Avatar answered Nov 14 '22 23:11

cdeszaq