2012-06-28 3 views
0

У меня есть набор переключателей на моей странице. Что касается изменения, я хочу знать, какая кнопка была снята, но на событии onchange$(this) ссылается на новую выбранную кнопку - есть ли способ получить старую невыбранную?Получение старой радиокнопки при изменении

window.old = null; 
    $('.radio').change(function(){ 
    alert($(this).val()); // this is the selected 
    alert($(window.old).val()); // this is the old one 
    }) 

ответ

2

Просто сохраните последний щелкнул радио переменной,

window.old = null; 

$(document).ready(function() { 
    window.old = $('.radio:checked'); 
}); 

$('.radio').change(function() { 
    alert($(this).html()); 

    if (window.old) { 
     alert($(window.old).html()); 
    } 

    window.old = this; 
}) 
+0

Обновленный мой код, чтобы установить начальное значение; –

1

Сохранить переключатель по щелчку (до изменения), и читать переключатель на новый один клик, следующий код:

window.old = null; 
$('.radio').click(function() { 
    // Store the current radio on click, before it changes 
    window.old = this; 
}).change(function() { 
    // Do something with the old radio value after the change 
    console.log('previous radio:', window.old); 
});​ 

Смотреть демо-http://jsfiddle.net/JL8V2/

0

Без Globals

$('input[type="radio"]').click(
 
    function (e) 
 
    { 
 
     var me = $(this); 
 
     var grp = $("input[type='radio'][name='" + me.attr('name') + "']"); 
 
     if (me.val() === me.data('last-val')) 
 
     { 
 
      me.prop('checked', false); 
 
      grp.data('last-val', null); 
 
     } 
 
     else 
 
     { 
 
      grp.data('last-val', me.val()); 
 
     } 
 
    } 
 
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 

 
<fieldset > 
 
    <legend> Group 1 </legend> 
 
    <label> 
 
    <input type="radio" name='grp1' value='1'/> 
 
     You can select me 
 
    </label> 
 
    <label> 
 
    <input type="radio" name='grp1' value='2'/> 
 
     But you can 
 
     </label> 
 
    <label> 
 
    <input type="radio" name='grp1' value='3'/> 
 
     Change your idea either 
 
     </label> 
 
</fieldset> 
 

 
<fieldset > 
 
    <legend> Group 2 </legend> 
 
    <label> 
 
    <input type="radio" name='grp2' value='1'/> 
 
     Just give another click 
 
    </label> 
 
    <label> 
 
    <input type="radio" name='grp2' value='2'/> 
 
     But remember, for this work 
 
     </label> 
 
    <label> 
 
    <input type="radio" name='grp2' value='3'/> 
 
     Values must be unique in each group 
 
     </label> 
 
</fieldset>