javascript - 如何将复选框设置为带有确认消息的按钮?

标签 javascript python django checkbox django-templates

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

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

要做的任务:

"If I click on checkbox it redirect to page with an endpoint which change value of checkbox from on to off"

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

复选框代码:

<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>

And what is happening here?

  1. When I click directly on checkbox there appears a confirmbox when I click "OK", checkbox change state but request is not send...
  2. When I click outside checkbox there is confirmbox and when I click "OK" I'm correctly redirected to request site.

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

我尝试在 div 之前、div 之后、标签之前、标签内部...都没有成功。

我将不胜感激!

最佳答案

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

你必须做的是在你的模板中创建一个输入复选框

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

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

<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>
                });
        }

      }
    }

关于javascript - 如何将复选框设置为带有确认消息的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51401886/

相关文章:

javascript - 如何在reactJS状态下动态设置对象属性的值?

javascript - Angular 2 : Class Properties Not Updating On params retrieval

python - Pandas 从几个月到几周重新采样

django - 在django中,models.ImageField默认采用哪种格式

python - 同时使用两个注释表达式时出现错误结果

javascript - 提交表单验证

javascript - Safari 浏览器 chop POST 参数

python - Pandas 散点矩阵 - 直方图是什么意思?

当需要 HTTPS 和代理身份验证时,Python Mechanize 不起作用

python - Django:TypeError: 'is_active' 是此函数的无效关键字参数