How not to submit a form if no radio button is checked
I using PHP in order to create an HTML form.
The form has 3 radio buttons and a submit button. In the initial state of the form, none of the radio buttons is checked. I want to make the form not to be submitted if non of the radio buttons is checked. Is there any way to do that? I attached part of the PHP c开发者_运维问答ode. for($i=0; $i<$nChoices; $i++) {
$Text='<input type="radio" name="answer" value="' . $IdChoices[$i] . '"';
$Text.="> ". $Choices[$i] . "</input>";
$choiceoutput.= $Text."<br /><br />";
}
Thanks!
This javascript can be used for simple client-side validation. It's not considered safe to only validate on the client-side but if your purpose is to see if the user actually selected an value this will do. Otherwise further validation needs to be taking place in your php script.
<script type="text/javascript">
function validate()
{
var retval = false;
for (var i=0; i < document.myForm.r.length; i++)
{
if (document.myForm.r[i].checked)
{
retval = true;
}
}
return retval;
}
</script>
Simple form for putting it to work.
<form name="myForm" action="page.php" onsubmit="return validate()" method="post">
<input type="radio" id="r">
<input type="radio" id="r">
<input type="submit" value="ok">
</form>
You should use javascript validation, intercepting commit and checking if some button is checked. But remember, that you have to validate also on server side, cause JS can be ommited.
Or, if wide browser support is not your concern - HTML5 supports form constraints validation ( https://developer.mozilla.org/en/HTML/HTML5/Forms_in_HTML5 )
<input type="submit" value="Submit" name="B1" disabled="disabled">
Above is an example of a Disabled submit button. You will have to use JavaScript to remove the disabled="disabled" attribute from the Submit button once user checks the checkboxes you want them to check.
http://www.techchorus.net/disable-and-enable-input-elements-div-block-using-jquery
There's a bit of a reading that should get you to understand the logic a lot better! :)
精彩评论