使用JS confrim对话框验证单选按钮

validation on radio button with JS confrim dialog

本文关键字:验证 单选按钮 对话框 confrim JS 使用      更新时间:2023-09-26

我正在尝试禁用单选按钮上的check事件。这是scanrio。

在单选组中,如果选中了button1,并且用户单击button2,则用户将看到JS确认对话框,如果用户单击确定则将选中button2,如果用户点击取消,则先前选中的按钮Button1将保持选中状态。

这是我试过的。

<form id="myForm">
<input type="radio" checked="true" name="radioName" onclick="setData(this)" value="1" /> 1 <br />
<input type="radio" name="radioName" onclick="setData(this)"  value="2" /> 2 <br />
<input type="radio" name="radioName" onclick="setData(this)"  value="3" /> 3 <br />
</form>
function setData(ctrl)
{
  var r = confirm("The selected option contains data, unchecking this option will delete this data. Do you want to continue ?");
      if (r == true) {
      // clicked Radio button gets checked
      } else {
      // perviously checked button remains checked
       return false;
      }
  }

但我无法达到预期的效果。这是小提琴:http://jsfiddle.net/RhnvU/5547/

您尝试做的是正确的,除了在onclick处理程序中,您应该使用return调用函数,因为如果用户按下cancel,您将返回false。

试试这样的东西-

onclick="return setData(this)"

这是最新的小提琴-http://jsfiddle.net/RhnvU/5550/

尝试这个

function setData(ctrl) {
  var r = confirm("continue?");
  if (r == true) {
    // clicked Radio button gets checked
  } else {
    // perviously checked button remains checked
    event.preventDefault();
    return false;
  }
}

我建议使用onmousedown事件而不是.click()。这是因为它将在更改单选按钮的值之前做出决定,而不是在click已经设置了值之后做出决定。

因此HTML代码变成:

<input type="radio" checked="true" name="radioName" onmousedown="setData(this)" value="1" />

在Js文件中,只需根据选择值使用.checked属性:

if (r == true) {
        ctrl.checked = true;
      // clicked Radio button gets checked
      } else {
       return false;
      }

这是工作小提琴

详细说明:它将做以下事情:

  1. 当你点击一个单选按钮时,它会触发onmousedown事件
  2. onmousedown事件处理程序将检查您是否单击了"确定"或"取消"
  3. 如果它是"ok",它将检查单选按钮的新值
  4. 如果是"取消",它将不起任何作用,因此单选按钮的旧值保持不变
'e.keycode == 32' is used to trigger the same event in case of space key press. Hope this helps.   
 $('.button1').on('click keyup' , function(e){
                    if(e.keyCode == 32 || e.type=="click"){
                        //show your Dialog or pop-up
                        $('.popup').show();
                        $('#proceed').click(function(){
                            selectradioButton1();
                        });
                        $('#cancel').click(function(){
                            $('.popup').hide();
                        });
                    }
                });
    $('.button2').on('click keyup' , function(e){
                    if(e.keyCode == 32 || e.type=="click"){
                        selectradioButton2();
                    }
                });
    function selectradioButton1() {
        $('#radiobtn1').attr('checked', true);
        $('#radiobtn2').attr('checked', false);
    }
    function selectradioButton1() {
        $('#radiobtn2').attr('checked', true);
        $('#radiobtn1').attr('checked', false);
    }