我正在使用Ruby on Rails 3.2.2和jquery-rails-2.0.2。在我的表单中,我有许多单选按钮,如果用户不接受确认消息,我想检查上一个选择的单选按钮。我想我可能会实现如下内容
<%= form.radio_button(:name_1, 'value_1', { :onclick => ('selectRadio(this)') }) %>
<%= form.radio_button(:name_2, 'value_2', { :onclick => ('selectRadio(this)') }) %>
<%= # Other radio buttons %>
<%= form.radio_button(:name_n, 'value_n', { :onclick => ('selectRadio(this)') }) %>
<script type="text/javascript">
function selectRadio(radiobutton) {
var confirm_message = confirm('Are you sure?');
if (confirm_message) {
# Check the selected radio button.
} else {
# Re-check the previous selected radio button.
}
}
</script>
。但我没有"重新检查以前选择的单选按钮"的解决方案。可能吗?如果是这样,如何做到这一点?
您可以使用以下代码块来执行此操作
我假设您考虑的所有单选按钮都有一个共同的类,例如radios
var prev = $(".radios:checked");
$(".radios").change(function() {
if(confirm('Are you sure?')){
prev = $(this);
}else{
prev.prop('checked','checked');
}
});
工作小提琴
参考: $.change $.prop
一种解决方案是在用户检查时存储用户的选择,并在必要时将其还原。
试试下面...
<script type="text/javascript">
// first get checked radio button where myform is your form in which radiobuttons reside
var lastRadio = $("#myform input[type='radio']:checked");
function selectRadio(radiobutton) {
var confirm_message = confirm('Are you sure?');
if (confirm_message) {
lastRadio = $(radiobutton);
# Check the selected radio button.
} else {
lastRadio.attr('checked',true);
# Re-check the previous selected radio button.
}
}
</script>