如果用户不接受JS确认消息,如何检查上一个选定的单选按钮

How to check the previous selected radio button if an user doesn't accept JS confirm message?

本文关键字:检查 上一个 单选按钮 何检查 JS 不接受 用户 确认 消息 如果      更新时间:2023-09-26

我正在使用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>