Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1039 How can I ensure that one radio button is checked and that the relevant text field is not empty?

You are here: irt.org | FAQ | JavaScript | Form | 3.4 | Q1039 [ previous next ]

Try something like this:

<script language="JavaScript"><!--
function validate(what) {
    for (var i=0;i<what.radioButtonName.length;i++) {
        if (what.radioButtonName[i].checked && what.elements['textFieldName' + i].value != '')
            return true;
    }
    alert('You must choose an option, and complete the form field');
    return false;
}
//--></script>

<form name="formName" onSubmit="return validate(document.forms.formName)">
<input type="radio" name="radioButtonName"> <input type="text" name="textFieldName0"><br>
<input type="radio" name="radioButtonName"> <input type="text" name="textFieldName1"><br>
<input type="radio" name="radioButtonName"> <input type="text" name="textFieldName2"><br>
<input type="submit">
</form>

Note: A lone radio is not valid HTML - you need two - if only one, use a checkbox. IE seemingly does not create an array if there is only one.

©2018 Martin Webb