1

我如何使 :confirm=>"Are you sure" 有条件?我有这个代码

<div id="container"><%= form_for @question,:remote=>true,:html=>{:name=>"question"} do |f|%>
    <p>
        <div class ="row">
        <%= label_tag(:topic,@displayquestion.question_text,:class=>"form-label")%>
        </div>
    </p>
    <p>
    <label>
    <%= f.radio_button(:answer, "1") %>
    <%= label_tag(:choice1,@displayquestion.choice1,:class=>"form-label")%>
    </label>
    </p>
    <p>
    <label>
    <%= f.radio_button(:answer, "2") %>
    <%= label_tag(:choice2,@displayquestion.choice2,:class=>"form-label")%>
    </label>
    </p>
    <p>
    <label>
    <%= f.radio_button(:answer, "3") %>
    <%= label_tag(:choice3,@displayquestion.choice3,:class=>"form-label")%>
    </label>
    </p>
    <p>
    <label>
    <%= f.radio_button(:answer, "4") %>
    <%= label_tag(:choice4,@displayquestion.choice4,:class=>"form-label")%>
    </label>
    </p>
    <%= f.submit(:value=>next,:class =>"button",:disable_with=>'loading') %>
<% end %></div>

我想让它只有在没有选择单选按钮时才会提示。我有这个 jQuery 代码,如果没有选择单选按钮,它将提示用户。

$(document).ready(function(){

   $("#container").on("click", ".edit_question", function(event){

     if (!$("input[@name='question[answer]']:checked").val()) {
       confirm('Are sure you want to submit a blank answer?');
    }

   if (!$("input[@name='answer[]']:checked").val()) {
       confirm('Are sure you want to submit a blank answer?');
    }

}
);
});

问题是即使我点击取消,也发送了ajax请求,如何拦截ajax请求调用jQuery代码?

谢谢指点!我是这样做的,它有效!

$(document).ready(function(){

   $("#container").on("submit", ".edit_question", function(event){
    var reply = true;
     if (!$("input[@name='question[answer]']:checked").val()) {
       reply=confirm('Are sure you want to submit a blank answer?');
    }

   if (!$("input[@name='answer[]']:checked").val()) {
       reply=confirm('Are sure you want to submit a blank answer?');
    }
   return reply;
}
);
});
4

1 回答 1

2

您的 click 函数需要返回 false 才能取消页面提交。Confirm() 返回一个布尔值,true 表示确定,false 表示取消。

例子:

$("#container").on("click", ".edit_question", function(event){

    if (!$("input[@name='question[answer]']:checked").val()
        || !$("input[@name='answer[]']:checked").val()  ) {
        return confirm('Are sure you want to submit a blank answer?');
    }
    return true;
}
于 2012-09-28T15:12:12.333 回答