Reputation: 24121
I am using Django and Python to write a website. In one webpage, I have an HTML form, with a set of radio buttons and a submit button. On form submission, I want to verify that a radio button has in fact been selected, rather than all radio buttons left black as is default.
One way of doing this is to do the check on the server side. I would check the POST data, and see whether the relevant field, indicating the selected radio button, has been set. If this field has not been set, then I would return to the same webpage, and display the message "Please try again". This works fine for me.
However, this seems a bit of an overkill. Is there any way I can do this same check in Javascript (jQuery), and return this same webpage and error message?
Upvotes: 0
Views: 194
Reputation: 301
HTML & JavaScript:
<html>
<head>
<script type="text/javascript">
function validateRadioButtons(){
var radio = $('input:radio[name="IdName"]:checked');
if(radio.length == 0)//no buttons selected
{
$('ValidationError').text("you haven't selected any buttons!");
return;
}
$('ValidationError').text(radio.val()+' is selected');
}
</script>
</head>
<body>
<form>
<div>
<span>
<input type="radio" name="IdName" value="Id1"/>
Id1
<input type="radio" name="IdName" value="Id2"/>
Id2
</span>
<div id="ValidationError" name="ValidationError">
</div>
</div>
<input type="submit" value="Submit" onclick="return validateRadioButtons();" />
</form>
</body>
</html>
Upvotes: 1
Reputation: 400
You can check one radio-button by default by adding checked
in the input field of the button you want to check by default. That ensures at least one input box will always be selected.
<input type="radio" checked />
Upvotes: 1
Reputation: 4775
You can use Django-parsley to attach client side validation to your existing forms.
Upvotes: 2
Reputation: 225
Using JQuery the validation code will be something like this.
$('form').submit(function(){
if($('input[type=radio]:checked').val() == ''){
alert('please select radio buttion');
return false;
}
}
Upvotes: 1