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

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


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

最佳答案

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

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

10-15 04:08