AlexandrX
AlexandrX

Reputation: 838

Is there a way to get previous radio value in "click" or "change" event handler?

I need to know if user clicked to already checked radio or he made a new choice. Now I detect it via "focus", "click" and "change" events combination (store old value in "focus", and compare it with current in "click" or "change" to detect and handle click to already checked radio).

Just to clarify: I cant store previous state in click handler, because I could not get the the initial state here; or "focus+click" or "load+(prev)click+click";

But it looks like a hack for me, and I assume that there is a more straight way to do this using built-in jquery features, using just one event handler. Is there something like this?

Thanks in advance!

Upvotes: 1

Views: 5087

Answers (2)

Johan Maes
Johan Maes

Reputation: 1442

You could also keep a copy of the checked value in a data attribute which you then update accordingly in the click handler:

$('input[name=test]').click(function(){
    var previous = $('input[name=test][data-checked=true]')[0];
    console.log(`previous: ${previous.id}`);
    console.log(`this: ${this.id}`);
    
    // the button was already checked so nothing needs to happen
    if (this.id === previous.id) {
      return;
    }
    
    // update data-checked: add attribute to the current button, remove for the rest
    $(this).attr('data-checked', 'true');
    $('input[name=test]:not(:checked)').removeAttr('data-checked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test1" type='radio' name='test' value='First' checked data-checked='true'>
<label for="test1">First</label><br>

<input id='test2' type='radio' name='test' value='Second'>
<label for="test2">Second</label><br>

<input id='test3' type='radio' name='test' value='Third'>
<label for="test3">Third</label><br>

Upvotes: 2

Dacklf
Dacklf

Reputation: 700

Use mousedown as @Bukent Vural suggests.

Get the current value before change with $('input[name=test]:checked').val();, where 'test' is the name of your radio inputs.

Take a look at this JSFiddle.

EDIT

If you want to detect label clicks as well, a second event handler needs to be added:

$('label').click(function() {
       labelID = $(this).attr('for');
       $('#'+labelID).trigger('mousedown');
});

Check the updated JSFiddle.

Upvotes: 2

Related Questions