Radio button Validation not working - javascript

I need to validate radio buttons and I am struggling to find where the problem is coming from.
Basically put, what happens when I submit, it does not validate the form and all it's fields. I know it is this function that is causing the problem, because when it is taken out of the .js file the form validates properly.
Below is the part of my HTML file containing the radio buttons
<tr>
<th align="left">Driver Required: </th>
<td>
<input type="radio" name="Driver" value="Yes" id="radio_error"> Yes
</td>
</tr>
<tr>
<td><br></td>
<td>
<input type="radio" name="Driver" value="No" id="radio_error"> No
</td>
</tr>
<tr><th><br></th></tr>
<tr>
<th align="left">Insurance: </th>
<td>
<input type="radio" name="Insurance" value="None" id="radio_error"> None
</td>
</tr>
<tr>
<td><br></td>
<td>
<input type="radio" name="Insurance" value="CDW" id="radio_error"> Collision Damage Waiver
<br>
<input type="radio" name="Insurance" value="LI" id="radio_error"> Liability Insurance
<br>
<input type="radio" name="Insurance" value="PAI" id="radio_error"> Personal Accident Insurance
<br>
<input type="radio" name="Insurance" value="PEC" id="radio_error"> Personal Effects Coverage
</td>
</tr>
The following lines of code is from the .js file. I have a validate function, which I am sure isn't the problem.
function checkDriverRadio()
{
var yesOrNo = "";
var len = document.ClientForm.Drvier.length;
var i;
for (i = 0; i < len; i++)
{
if (document.ClientForm.Drvier[i].checked)
{
yesOrNo = document.ClientForm.Driver[i].value;
break;
}
}
if (!document.ClientForm.Driver.checked)
{
document.getElementById("radio_error").innerHTML = "No option selected";
return false;
}
else
{
document.getElementById("radio_error").innerHTML = "";
return true;
}
}
function checkInsuranceRadio()
{
var option = "";
var len = document.ClientForm.Insurance.length;
var i;
for (i = 0; i < len; i++)
{
if (document.ClientForm.Insurance[i].checked)
{
option = document.ClientForm.Insurance[i].value;
break;
}
}
if (!document.ClientForm.Insurance.checked)
{
document.getElementById("radio_error").innerHTML = "No option selected";
return false;
}
else
{
document.getElementById("radio_error").innerHTML = "";
return true;
}
}

I think there is a misspelling error...
if (document.ClientForm.Drvier[i].checked)
{
yesOrNo = document.ClientForm.Driver[i].value;
break;
....your file name is Driver not Drvier.
I hope this helps.

I realize all your radio buttons have the same Id's, Radio buttons are grouped by name="someName" which you have done and as mentioned by other answers you have some typographical errors you need to look at. I created a simple validation in this fiddle kindly check it out if it helps.
https://jsfiddle.net/mr_odoom/17xwdL79/

Related

Div not showing when radio button checked

I have a radio button that will show a div with an input text when it is checked 'NO'. But it is not showing the div, however when I play around the radio button then the div will show. Where am I missing?
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
if (firstCheckbox.checked == true) {
rmk.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmk.style.display = "block";
document.getElementById("rmk").required = true;
}
}
<div>
<label>Have you registered the course?</label>
<table border=0>
<tr>
<td>YES </td>
<td><input type="radio" name="register" value="Y" id="check1" onclick="CheckboxCheck('first')">  </td>
<td>NO </td>
<td><input type="radio" name="register" value="N" checked id="check2" onclick="CheckboxCheck('second')"></td>
</table>
</div>
<div id="rmk" style="display:none">
<label>Reasons</label>
<input type="text" name="remarks" class="form-control">
</div>
There are a few structure and accessibility proposals going on in this suggestion but I think strictly speaking, the easiest solve for you is to invoke the function on page load. Give this example a look:
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
var rmkdiv = document.getElementById("rmk-div");
if (firstCheckbox.checked == true) {
rmkdiv.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmkdiv.style.display = "block";
rmk.required = true;
}
}
CheckboxCheck()
<div>
<p>Have you registered the course?</p>
<label>
YES<input
type="radio"
name="register"
value="Y"
id="check1"
onclick="CheckboxCheck()"
/></label>
<label>NO
<input
type="radio"
name="register"
value="N"
checked
id="check2"
onclick="CheckboxCheck()"
/>
</label>
<div id="rmk-div" style="display: none">
<label>Reasons</label>
<input id="rmk" type="text" name="remarks" class="form-control" />
</div>
</div>
Your input field will only be visible when the function CheckboxCheck is executed. Since "NO" is checked from the beginning, the function will not be executed because it is only called when a change takes place.

form JavaScript function checkAnswer not loading pages

I have a form that I've been working on for a school project and I can't figure out what's wrong with the JavaScript checkAnswer function. The form and all the buttons work, but when I hit the submit button, all that loads is a blank page. I have tried researching forms but I can't figure out where my code is wrong. Why won't it check anything?
Here is the form from my index.html file:
<script src="CheckForm.js"></script>
<form method="post" action="return checkAnswer(this, '1', 'Correct.html',
'Incorrect.html');" name="quizForm" id="quizForm">
<input type="radio" name="choice" value="1"/>
<script>getMusician(answer1);</script><br/>
<input type="radio" name="choice" value="2"/>
<script>getMusician(answer2);</script><br/>
<input type="radio" name="choice" value="3"/>
<script>getMusician(answer3);</script><br/>
<input type="radio" name="choice" value="4"/>
<script>getMusician(answer4);</script><br/>
<input type="submit" value="Submit"/>
</form>
This is the code from my CheckForm.js file:
function checkAnswer(quizForm, Answer, CorrectPage, IncorrectPage)
{
var i = 0;
var j = null;
for(;i<quizForm.elements.length();i++)
{
if(quizForm.elements[i].value.checked)
j = quizForm.elements[i].value;
}
if(j === null)
{
windows.alert("Please make a selection.");
return false;
}
if(j == Answer)
{
document.location.href = CorrectPage;
}
else
{
document.location.href = IncorrectPage;
}
return false;
}
You shouldn't need a form for this. It looks like you are creating a static site so I would remove the form and the rest you are pretty close with. Here is a working example for you.
Also it looks like you are creating some sort of quiz site. Be aware users can use the developer console to see the correct answer (the first input to checkAnswer() method)- I thought it would be worth mentioning that.
function checkAnswer(answer, correctPage, incorrectPage) {
var i = 0;
var j = null;
var inputs = document.getElementsByClassName('musician');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
j = inputs[i].value;
}
if (j == null) {
alert("Please make a selection.");
return false;
}
if (j == answer) {
console.log('CORRECT!')
document.location.href = CorrectPage;
} else {
console.log('incorrect :(')
document.location.href = IncorrectPage;
}
}
<div id="inputContainer">
<input type="radio" name="choice" class="musician" value="1" />musician 1
<br/>
<input type="radio" name="choice" class="musician" value="2" />musician 2
<br/>
<input type="radio" name="choice" class="musician" value="3" />musician 3
<br/>
<input type="radio" name="choice" class="musician" value="4">musician 4
<br/>
</div>
<input type="button" onclick="checkAnswer('1', 'Correct.html',
'Incorrect.html')" value="Submit" />

Set a condition for elements with the same class in javascript

I have a couple of checkboxes that I want to check if the user selected them,
If he selected 2, then he can't select more.
The problem is that I use the them several times in diffrent rows and they have the same class.
How can I check in javascript if only 2 checkboxes are selected in each group of buttons?
HTML:
<td>
<!-- First Group of Buttons -->
<p>Barcelona</p>
<label class="dir-bet" type="checkbox">Barcelona Win</label>
</td>
<td class="middle-table">
<p>VS</p>
<label class="dir-bet" type="checkbox">Draw</label>
</td>
<td class="team-header">
<p>R.Madrid</p>
<label class="dir-bet" type="checkbox">R.MadridWin</label>
</td>
</tr>
<tr>
<td>
<!-- Second Group of Buttons -->
<p>Barcelona</p>
<label class="dir-bet" type="checkbox">Barcelona Win</label>
</td>
<td class="middle-table">
<p>VS</p>
<label class="dir-bet" type="checkbox">Draw</label>
</td>
<td class="team-header">
<p>R.Madrid</p>
<label class="dir-bet" type="checkbox">R.Madrid Win</label>
</td>
Java-Script:
var list = document.getElementsByClassName("dir-bet");
var checkBet = function(){
var checkNum = 0;
for (i = 0; i < list.length; i++){
if(list[i].getAttribute("checked")){
checkNum++;
}
}
if (checkNum<2 ) {
if(this.getAttribute("checked")){
this.setAttribute("checked","");
this.classList.remove ("prime-bg", "prime-clr");
}else{
this.setAttribute("checked","true");
this.classList.add ("prime-bg", "prime-clr");
}
}else{
if(this.getAttribute("checked")){
this.setAttribute("checked","");
this.classList.remove ("prime-bg", "prime-clr");
}
}
};
for (i = 0; i < list.length; i++){
list[i].addEventListener("click", checkBet);
}
You could check in which table row your click happens, and then get only the list of dir-bet class elements that are within that row. Then apply your counting logic on that smaller list of elements.
With some other improvements, your checkBet function could look like this:
var checkBet = function () {
var checked = this.getAttribute("checked");
if (!checked) { // a count is only needed when adding a check mark:
var list = this.parentElement.parentElement.getElementsByClassName("dir-bet");
var checkNum = 0;
for (var i = 0; i < list.length; i++) {
if (list[i].getAttribute("checked")) {
checkNum++;
}
}
if (checkNum >= 2) return; // reject
}
// toggle the check status
checked = !checked;
this.setAttribute("checked", checked ? "true" : "");
this.classList.toggle("prime-bg", checked);
this.classList.toggle("prime-clr", checked);
};
If jQuery is an option, here's a solution :
let $checkboxes = $("input[type=checkbox]")
$checkboxes.click(() => {
$checkboxes.attr("disabled", false)
if ($("input[type=checkbox]:checked").length == 2) {
$("input[type=checkbox]:not(:checked)").attr("disabled", true)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Can check only 2 checkboxes</h2>
<br/>
<input type="checkbox"/><span>Checkbox 1</span><br/>
<input type="checkbox"/><span>Checkbox 2</span><br/>
<input type="checkbox"/><span>Checkbox 3</span><br/>
<input type="checkbox"/><span>Checkbox 4</span><br/>
<input type="checkbox"/><span>Checkbox 5</span><br/>
<input type="checkbox"/><span>Checkbox 6</span><br/>
<input type="checkbox"/><span>Checkbox 7</span><br/>
<input type="checkbox"/><span>Checkbox 8</span><br/>
<input type="checkbox"/><span>Checkbox 9</span><br/>
<input type="checkbox"/><span>Checkbox 10</span><br/>

how to select multiple checkbox validation in javascript

Here is my Form. I need validation in JavaScript.
At least one checkbox selected in validation.
I hop you all are understand what I need.
please give me solution for that.
If any query then feel free ask.
<form action="#" method="post" name="studentregistration" onsubmit="return(validate());">
<table cellpadding="3" width="100%" align="center" cellspacing="3">
<tr>
<td>Hobby</td>
<td>
<input type="checkbox" name="hobby" value="Chess" id="hobby">Chess
<input type="checkbox" name="hobby" value="Music" id="hobby">Music<br>
<input type="checkbox" name="hobby" value="Cricket" id="hobby">Cricket
<input type="checkbox" name="hobby" value="Reading" id="hobby">Reading
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit Form" value="Submit Form" id="submitform">
</td>
</tr>
</table>
</form>
If you're trying to validate that at least one checkbox is checked, then this should work for you using jQuery:
$('input[type="checkbox"]:checked').length > 0
In "pure" js, you could remove the onsubmit attribute and do this instead:
document.querySelector('form[name="studentregistration"]').onsubmit = function(e) {
e.preventDefault();
var cbx = document.querySelectorAll('form[name="studentregistration"] input[name="hobby"]:checked');
if(cbx.length > 0) {
// at least one checked - do something
}
else {
// none checked
}
}
See a live demo!
Complete solution.
In order to submit the form after validation you must use:
document.getElementById("myForm").submit();
document.getElementById("submitform").addEventListener("click",submit_form);
function submit_form(e){
var ob = "";
var chess = document.getElementById("hobby1").checked;
var music = document.getElementById("hobby2").checked;
var cricket = document.getElementById("hobby3").checked;
var reading = document.getElementById("hobby4").checked;
if(chess == true){
ob += "hobby: chess selected!\n";
}
if(music == true){
ob += "hobby: music selected!\n";
}
if(cricket == true){
ob += "hobby: cricket selected!\n";
}
if(reading == true){
ob += "hobby: reading selected!\n";
}
if(ob==""){
alert("No hobbys selected");
}
else{
alert(ob);
//document.getElementById("myForm").submit();
}
//for testing purposes
e.preventDefault();
return false;
}
<form id = "myForm" action="#" method="post" name="studentregistration">
<table cellpadding="3" width="100%" align="center" cellspacing="3">
<tr>
<td>Hobby</td>
<td>
<input type="checkbox" name="hobby" id="hobby1">Chess
<input type="checkbox" name="hobby" id="hobby2">Music<br>
<input type="checkbox" name="hobby" id="hobby3">Cricket
<input type="checkbox" name="hobby" id="hobby4">Reading
</td>
</tr>
<tr>
<td>
<input type="button" name="Submit Form" value="Submit Form" id="submitform">
</td>
</tr>
</table>
</form>
if($("#hobby").is(':checked')){
alert("checkbox checked");
}
else{
alert("Please select at least one checkbox");
}
Here is another easy answer
var test = document.getElementsByName("hobby[]");
if(test[0].checked==false && test[1].checked==false && test[2].checked==false && test[3].checked==false)
{
alert("Please Check");
return false;
}

Radio button validation (alert box) confirmation and rejection

I'm working on a HTML document which is an exam submission form. I've completed almost all of the set tasks however, I'm having trouble validating radio buttons. I've searched on stackoverflow however, the answers do not meet the criteria of the question. My completed code is shown below.
I'm having trouble with the bold part of this task:
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Below is the code working, excluding the validation of the radio buttons. Seperatley, I have the code which doesn't work when implemented into the function validateForm().
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value.length!== 4) {
msg+="Your Examination Number should be 4 digits.\n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr></tr>
<tr>
<td id="name">Name</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td id="subject">Subject</td>
<td>
<input type="text" name="subject" />
</td>
</tr>
<tr>
<td id="examinationno">Examination Number</td>
<td>
<input type="text" name="examno" />
</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="GCSE" />GCSE</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="AS" />AS</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="A2" />A2</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Submit" onClick="return validateForm();" />
</td>
<td>
<input type="reset" name="Reset" value="Reset" />
</td>
</tr>
</table>
</form>
Based on the current code, why won't the following validate when added into the function?:
if(document.getElementById('GCSE').checked)
{examtype = "GCSE";
}
if(document.getElementById('AS').checked)
{examtype = "AS";
}
if(document.getElementById('A2').checked)
{examtype = "A2";
}
if(confirm("You have selected"+examtype+.Continue?")){
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
else{
alert("Action cancelled");
return false;
}
// Retrieving the checked radio button value
function getRadioValue (frmName, rbGroupName)
{
var radios = document[frmName].elements[rbGroupName];
for (var i=0; i <radios.length; i++)
{
if (radios[i].checked)
{
return radios[i].value;
}
}
return false;
}
Call the getRadioValue() inside validateForm()
// examtype gets false or GCSE or AS or A2
var examtype = getRadioValue ("ExamEntry", "examtype");
"Continue" is a keyword. So you have to wrap it in apostrophes("). I could not get the structure of if-statements, I made some changes. I hope this is what you are looking for..
if(confirm("You have selected"+examtype+". Continue?")){
if(msg==""){
alert(msg);
return result;
}
else{
alert("Action cancelled");
return false;
}
}

Categories

Resources