I am going to use javascript to validate my radio buttons. What I need to do is that I want to use document.write so that the validation message appears in the <div> “radioalert” but I don’t know how to do this. Instead it is displaying the message as its own on the page.
Below is javascript function to check radio buttons:
function validation(){
if(sessionform.sessionNo[0].checked==false && sessionform.sessionNo[1].checked==false && sessionform.sessionNo[2].checked==false
&& sessionform.sessionNo[3].checked==false && sessionform.sessionNo[4].checked==false){
document.write("Please select the Number of Sessions you Require");return false
;}
If you use document.write() to output to the page while it is still loading, then the output will be on the current page. If you use document.write() after the page has finished loading, as in this case, the output goes to a new document.
What you need to do in this case is use getElementById() to get an object reference to the element you want to display the message in and then assign the message to the innerHTML property of the element’s object reference. And then the error message will appear on your current opened web page.
Also, checking each radio button individually is a very inefficient way of doing it and results in bloated code. A much more efficient way is to use a single loop to loop through your array of radio buttons to ensure one of them is checked.
Looking at an example in stackoverflow which another user asked something like this, I tried this but this didn’t work:
var radioAlert = document.getElementById("radioAlert");
function validation(){
if(sessionform.sessionNo[0].checked==false && sessionform.sessionNo[1].checked==false && sessionform.sessionNo[2].checked==false
&& sessionform.sessionNo[3].checked==false && sessionform.sessionNo[4].checked==false){
radioAlert.innerHTML = "Please select the Number of Sessions you Require";
;}
I changed div tag id from ‘radioalert’ to ‘radioAlert’
Thanks for that simple validator code you have showed me. I can see why it will be better than my example. It does however have one problem though. If I do not select a radio button then it states “click a radio button” message which is obviously correct. But if I do choose a radio button and submit, the message does not change, it still states “click a radio button” and not the other message.