Validate dynamic radio buttons
Reez0
I would like to know how to check if a radio button is selected before the user clicks submit. Currently, submissions are allowed if nothing is selected.
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})
Is my approach wrong? Should I be using a form with radio buttons for validation?
Gabriel Tufis
(jQuery, but logic should apply)
The way I do this is to create an event where the user clicks a radio button to give me the ID of that particular radio button. Using the ID, you know that the user pressed the witch radio button.
$("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>
EDIT: If you just want to make sure the user clicks the radio button then just add at the end
<input id="3" type="radio" name="lala" required>