验证动态单选按钮

时间:2018-03-30 23:04:24

标签: python django

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

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

views.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})

我的方法有误吗?我应该使用单选按钮的表单进行验证吗?

1 个答案:

答案 0 :(得分:2)

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

编辑:如果您只是想确保用户点击一个单选按钮,只需在最后添加

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