我是初级 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?
- When I click directly on checkbox there appears a confirmbox when I click "OK", checkbox change state but request is not send...
- 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/