Get the value of the radio button that was selected before the user selects a new one
Asked Answered
H

8

18

If I have 3 radio buttons, is there a way through jQuery of finding out the value of the one that was selected before the user clicks a new one?

<div id="radio-group">
    <input type="radio" id="radio-1" name="radios" value="1" checked="true" />
    <input type="radio" id="radio-2" name="radios" value="2" />
    <input type="radio" id="radio-3" name="radios" value="3" />
</div>

In the example avove, if the user clicks on radio-3, I need a way to get 1, so that I can carry out some formattion to it. Thanks.

Huang answered 15/6, 2012 at 14:31 Comment(1)
Save the value in some variable when user clicks it,, this way you can have previous value for next clickSarasvati
P
16

I would save the pressed values to an array and edit hidden value with that.

http://jsfiddle.net/BQDdJ/6/

HTML

<div id="radio-group">
    <input type="radio" id="radio-1" name="radios" value="1" checked="true" />
    <input type="radio" id="radio-2" name="radios" value="2" />
    <input type="radio" id="radio-3" name="radios" value="3" />
    <input type="hidden" id="radio-previous" name="radio-previous" />
</div>​

JavaScript

$(document).ready(function(){
    var clicks = new Array();
    clicks[0] = 1 //this should be the default value, if there is one

    $('input[name$="radios"]').change(function(){
       clicks.push($(this).val()) 
       $('#radio-previous').val(clicks[clicks.length-2])
    })
})

Partridgeberry answered 15/6, 2012 at 14:42 Comment(1)
Instead of clicks[0] = 1 you can do clicks[0] = $('input[name="radios"][checked="true"]').val(); which will return the default value without hard-coding it in the JavaScript.Phosgenite
M
28

You can use mouseup and change event. In mouse up you will get the value of radio button that is selected before selecting other radion button and change event will give the new selection of radio button.

Live Demo

$('input[name=radios]').mouseup(function(){
    alert("Before change "+$('input[name=radios]:checked').val());
}).change(function(){
    alert("After change "+$('input[name=radios]:checked').val());
})​;
Minacious answered 15/6, 2012 at 14:33 Comment(1)
Great answer, +1. However is reacts in strange ways when clicking directly on the radio button and the option above (although doesn't deal directly with DOM events) is cleaner.Julio
P
16

I would save the pressed values to an array and edit hidden value with that.

http://jsfiddle.net/BQDdJ/6/

HTML

<div id="radio-group">
    <input type="radio" id="radio-1" name="radios" value="1" checked="true" />
    <input type="radio" id="radio-2" name="radios" value="2" />
    <input type="radio" id="radio-3" name="radios" value="3" />
    <input type="hidden" id="radio-previous" name="radio-previous" />
</div>​

JavaScript

$(document).ready(function(){
    var clicks = new Array();
    clicks[0] = 1 //this should be the default value, if there is one

    $('input[name$="radios"]').change(function(){
       clicks.push($(this).val()) 
       $('#radio-previous').val(clicks[clicks.length-2])
    })
})

Partridgeberry answered 15/6, 2012 at 14:42 Comment(1)
Instead of clicks[0] = 1 you can do clicks[0] = $('input[name="radios"][checked="true"]').val(); which will return the default value without hard-coding it in the JavaScript.Phosgenite
G
3

"It's been a while" would be an euphemism but in case someone stumbles upon this issue:

Adil pointed me in the right direction, however mouseup only works for mouse-triggered events (duh), so I tried with focus and, since it also happens before change event, it works with, both, mouse and keyboard inputs (like when you change the radios status using the tab and arrow keys). So to gain access to the previously selected/checked item before the user interaction you use focus and to get the current item you use your good old change:

//html
    <input type="radio" id="radio-1" name="radios" value="1" />
    <input type="radio" id="radio-2" name="radios" value="2" />

//js
    //if currently checked item is radio-1
    $('[name=radios]').on('focus', function() {
        console.log($('[name="radios"]:checked').val()); //outputs 1
    });
    $('[name=radios]').change(function() {
        console.log($('[name="radios"]:checked').val()); //outputs 2
    });
Garv answered 5/3, 2018 at 17:25 Comment(0)
O
2

I had the same issue when trying to make a budget calculator with options, I solved it using a a var to hold the last value;

            var before = -1;
            $('input:checkbox, input:radio').click(function() {
                // +(str) =  number(str)
                var value = +$(this).val();
                if ($(this).is(":checkbox")) {
                    if ($(this).is(":checked")) {
                        total += value;
                    } else {
                        total -= value;
                    }
                }
                else {
                    if (before < 0) {
                        total += value;
                        before = value;
                    } else {
                        total -= before;
                        total += value;
                        before = value;
                    }
                }
                $("#sub-total").text(total * hourly_rate);
                if ($(this).is("[data-toggle]")) {
                    $("#" + $(this).attr("data-toggle")).slideToggle("fast");
                }
            });
Outing answered 10/1, 2014 at 16:28 Comment(0)
E
1

Just to complete #Adil's answer, if you have radios with text, if the user clicks the text, the previousRadio doesn't get updated. You can use the following:

<label>
   <input type="radio" name="radioName">
   text
</label>

And js:

var $previousRadio;
var $inputs = $('input[name=radioName]');
$inputs.parents("label").mouseup(function () {
    $previousRadio = $inputs.filter(':checked');
});
$inputs.change(function () {
    alert($previousRadio.val());
});
Elburt answered 18/3, 2016 at 11:36 Comment(0)
C
0

@Ville answer is correct for radio, here is for checkbox

<div id="radio-group">
    <input type="checkbox" id="radio-1" name="radios" value="1" data-prev="false" />
    <input type="checkbox" id="radio-2" name="radios" value="2" data-prev="false" />
    <input type="checkbox" id="radio-3" name="radios" value="3" data-prev="false" />
</div>

JS:

$('body').on("click", "[name='checkbox']", function () {
    $(this).attr("data-prev", this.checked);
});
Cotoneaster answered 17/2, 2022 at 9:49 Comment(0)
S
0

Small hack. Add old value of radio button selected before to values of radio buttons like this.

<div id="radio-group">
    <input type="radio" id="radio-1" name="radios" value="1|1" checked="true" />
    <input type="radio" id="radio-2" name="radios" value="1|2" />
    <input type="radio" id="radio-3" name="radios" value="1|3" />
</div>

In attribute like value="1|3" first data is old value, second data is new value. Values are separated by '|' symbol.

Subfloor answered 15/4, 2022 at 18:3 Comment(0)
M
0

I'm looking through this all and here's my take on this. Just save off the information you need within the Unchecked event. radio buttons can only have one event checked so on uncheck you will be delivered the element that was last checked. You can save that as a RadioButton previouslyChecked and read off information from that in the checked event.

Medan answered 21/4, 2022 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.