【问题标题】:Stop radio button from changing, show popup, then change radio button停止单选按钮更改,显示弹出窗口,然后更改单选按钮
【发布时间】:2014-07-08 19:31:35
【问题描述】:

我想要做的是阻止用户更改单选按钮,直到他们确认他们想要离开“页面”。单选按钮不应更改为他们单击的那个,直到他们单击弹出窗口中的按钮说“确定离开页面”。

此调用处理将页面更改为选定的单选按钮以及其他所有内容。仅当单击弹出窗口中的按钮时才应触发:

$("body").on("change", "input[type='radio'][name='quote-type']:checked", function(e){

//Change the radio button and everything else

});

这会处理弹出窗口和所有内容:

  $(function(){
    var LEAVEPAGE;
    //Radio button changes, so show a popup
    $("body").on("change", ".coverage-options-wrapper li:not(.custom) input[type='radio'][name='quote-type']", function(e){

         e.preventDefault();
         e.stopPropagation();
         LEAVEPAGE = e.currentTarget;

         //Show the popup to ask if you are sure you want to switch radio buttons

         });
    //Click the button in the popup to leave the page, so change the originally clicked radio button.
    $("body").unbind("click").on("click", ".leave-page", function(){

        $(LEAVEPAGE).prop("checked", true).trigger("change"); //triggers change for the first call to be run, to actually change the page

    });
});

发生的情况是单选按钮只是被更改了,它也显示了弹出窗口,但是它没有等待弹出窗口的响应。无论如何它只是切换。此外,当我单击.leave-page 按钮时,它会触发更改(假设它会加载归因于该按钮的新页面),但是它也会再次触发弹出窗口(因为它们都使用更改事件) .

我很困惑。

【问题讨论】:

  • 你能做一个小提琴吗?

标签: javascript jquery events dom


【解决方案1】:

DEMO

JS

var optionTarget;

$(":radio").click(function(e){
   e.preventDefault();
   optionTarget = e.target;
   $("#leave-dialog").show(); 
});

$("#leave-dialog button").click(function(){
   $("#leave-dialog").hide();
});

$("#leave-btn").click(function(){
    $(optionTarget).prop('checked', true);
});

HTML

<input type="radio" name="bleh" value="yes" checked>option 1
<input type="radio" name="bleh" value="no">option 2
<div id="leave-dialog">Are you sure?
    <br/>
    <button id="leave-btn">Yes</button>
    <button>No</button>
</div>

【讨论】:

  • 我以前用过这个,但是在 Chrome 和 IE 中它似乎不起作用,它仍然有错误。我现在正在尝试对其进行测试,但该应用程序现在无法正常工作。
  • 好的,是的,在 Chrome 中这样做对我不起作用。它不会切换单选按钮,但不会阻止在字段上触发“更改”事件。我需要不要在第一部分触发更改事件..
  • 嗯,小提琴演示适用于我在 Chrome 中。正如上面的 cmets 所说,您介意创建一个小提琴,或者至少显示一个演示站点吗?我们不知道您的 HTML 是什么样子,也不知道其他有效的脚本可能会导致某些东西无法正常工作。
  • 奇怪的是,演示确实可以正常工作,甚至我创建的演示也可以工作..jsfiddle.net/D2vvc 但是网站上发生的事情是更改事件正在被触发..无论出于何种原因,它都不在我的演示...
猜你喜欢
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
  • 2011-12-07
  • 2019-01-16
相关资源
最近更新 更多