Search code examples
jqueryradio-button

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


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.


Solution

  • 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])
        })
    })