gpt4 book ai didi

python - 动态单选按钮的验证

转载 作者:行者123 更新时间:2023-12-01 02:01:25 25 4
gpt4 key购买 nike

我想知道如何在用户单击提交之前检查单选按钮是否已被选中。目前,如果未选择任何内容,则允许提交。

删除.html

{%for laptop in laptops%}
<form action = "{%url 'laptops:delete'%}" method = "post" enctype="multipart/form-data">
{% csrf_token %}
<div class="radio">
<input type="radio" id = "laptop_{{laptop.id}}" name="laptopname" value = "{{laptop.id}}">
<label for = "laptop_{{laptop.id}}">{{laptop}}</label>
</div>
{%endfor%}
<input type="submit" value="Submit" id="delete-button"/>
</form>

View .py

#Gets id value from the 'laptopname' radio button
laptopid = int(request.POST.get('laptopname'))
#Finds matching id value
laptop = Laptop.objects.get(id=laptopid)
#Populates form with matching data
data = {'Name': laptop.Name, 'specification': laptop.specification,'warranty': laptop.warranty,
'condition':laptop.condition}
form = forms.MakeSale(initial=data)
return render(request, 'laptops/laptop_sale.html', {'form': form})

我的做法是不是错了?我应该使用单选按钮表单进行验证吗?

最佳答案

(jQuery 但逻辑应该适用)

我的做法是在用户单击单选按钮时创建一个事件,以便为我提供该特定单选按钮的 ID。通过 ID,您可以知道用户按下的单选按钮。

$("input").click(function () {
alert($(this).attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>

<input id="1" type="radio" name="lala">
<input id="2" type="radio" name="lala">
<input id="3" type="radio" name="lala">


<script type="text/javascript" src="Demo.js"></script>
</body>
</html>

编辑:如果您只是想确保用户单击单选按钮,只需在末尾添加 required

<input id="3" type="radio" name="lala" required>

关于python - 动态单选按钮的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49582517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com