【问题标题】:How to make checkbox as button with confirm message?如何使复选框成为带有确认消息的按钮?
【发布时间】:2018-12-26 08:47:06
【问题描述】:

我是初级 Django 开发人员。这是我在公司的第一个项目,我有一个前端任务。

前端对我来说是黑魔法,但我尽了最大努力,但在这里我完全迷失了;/

要做的任务:

“如果我点击复选框,它会重定向到一个端点发生变化的页面 复选框的值从开到关"

我写了所有的后端人员......甚至是某种前端,但它没有按我想要的那样工作。我已经尝试了很多组合,但我仍然不知道。

复选框代码:

<table>
    <thead>...</thead>
    <tbody>
        <td>
            <a href="{% url 'product_user_paid_change' tp_id=item.pk paid=item.paid %}" onclick="return confirm('For surechange - {{ item.full_name }}?')">
                <div class="checkbox m-15">
                    <label for="id_paid"><input type="checkbox"{% if item.paid == True %} checked{% endif %} ><i class="input-helper"></i></label>
                </div>
            </a>
        </td>
    </tbody>
</table>

这里发生了什么?

  1. 当我直接点击复选框时,会出现一个确认框 单击“确定”,复选框更改状态但未发送请求...
  2. 当我单击外部复选框时,出现确认框,当我单击“确定”时,我被正确重定向到请求站点。

当我直接点击复选框时如何使它工作......不仅仅是在外面? ;/

我尝试在 div 之前、div 之后、标签之前、标签内部......没有任何效果。

我将不胜感激!

【问题讨论】:

    标签: javascript python django checkbox django-templates


    【解决方案1】:

    它非常简单,而且我的编辑与 python 或 django 无关。

    你要做的就是在你的模板上创建一个输入复选框

    <input type="checkbox" id="my_awesome_checkbox">
    

    创建一个 javascript 函数或将代码绑定到该输入中的事件

    <input type="checkbox" id="my_awesome_checkbox" onchange="myCuteFunction">
    
    function myCuteFunction() {    
      var checkBox = document.getElementById("my_awesome_checkbox")
    
      if (checkBox.checked == true){
        let result = confirm("Hey! You really want to leave me here?");
        if (result){
            location.replace("the url you wan to go");
        }
    
      }
    }
    

    编辑:您想根据来自后端的信息更改复选框值吗?

    如果您可以使用 ajax 从您的端点获取您想要的响应并更改您的复选框

    因此,使用前面的代码,您可以调用 ajax 来访问您的后端,而不是更改您的 url 页面...而不是更改您的复选框的值

    function myCuteFunction() {    
          var checkBox = document.getElementById("my_awesome_checkbox")
    
          if (checkBox.checked == true){
            let result = confirm("Hey! You really want to leave me here?");
            if (result){
                $.ajax({
                    url: "<your endpoint>",
                      context: <necessary paramenters>
                    }).done(function() {
                      <your response to add your logic to change the checkbox>
                    });
            }
    
          }
        }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多