validate radio buttons for a quiz - javascript

Need to validate radio buttons am developing a quiz page i can only validate 1 set of radio buttons any help be great below is my code. If a user hits the submit button without answering a question I want a alert message displayed saying u must answer whatever question they didnt answer. Any ideas as to why the jquery wont work thanks
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$('#quizForm').on('submit', function() {
var emptyCount = 0;
$('li').each(function() {
var found = false;
$(this).find('input[type=radio]').each(function() {
if ($(this).prop('checked')) {
found = true;
}
});
if (!found) {
emptyCount++;
}
});
if (emptyCount > 0) {
alert('Missing checks:' + emptyCount);
return false;
}
return true;
</script>
<form action='mail.php' method='post' id='quizForm' id='1' name='quizForm' onSubmit='form()'>
<ol>
<li>
<h3>1 x 1 =</h3>
<div>
<input type='radio' name='answerOne' id='answerOne' value='A' />
<label for='answerOneA'>A)1</label>
</div>
<div>
<input type='radio' name='answerOne' id='answerOne' value='B' />
<label for='answerOneB'>B)2</label>
</div>
<div>
<input type='radio' name='answerOne' id='answerOne' value='C' />
<label for='answerOneC'>C)3</label>
</div>
</li>
<li>
<h3>1 x 6 =</h3>
<div>
<input type='radio' name='answerTwo' id='answerTwo' value='A' />
<label for='answerTwoA'>A)5</label>
</div>
<div>
<input type='radio' name='answerTwo' id='answerTwo' value='B' />
<label for='answerTwoB'>B)6</label>
</div>
<div>
<input type='radio' name='answerTwo' id='answerTwo' value='C' />
<label for='answerTwoC'>C)4</label>
</div>
</li>
<li>
<h3>2 x 8 =</h3>
<div>
<input type='radio' name='answerThree' id='answerThree' value='A' />
<label for='answerThreeA'>A)14</label>
</div>
<div>
<input type='radio' name='answerThree' id='answerThree' value='B' />
<label for='answerThreeB'>B)12</label>
</div>
<div>
<input type='radio' name='answerThree' id='answerThree' value='C' />
<label for='answerThreeC'>C)16</label>
</div>
</li>
</ol>
<input type="submit" />
</form>
</body>
</html>

First: you should not have the same id multiple times on one page. So the id of each answer should be different.
Anyway you can go through all the li elements and check if there's a checked radio in it.
$('form').on('submit', function() {
var emptyCount = 0;
$('li').each(function() {
var found = false;
$(this).find('input[type=radio]').each(function() {
if ($(this).prop('checked')) {
found = true;
}
});
if (!found) {
emptyCount++;
}
});
if (emptyCount > 0) {
alert('Missing checks');
return false;
}
return true;
});

Writing a custom validator for your code on here would probably just be excessive. I'd use bValidator and call it a day.
See their sections on "radio groups".
http://bojanmauser.from.hr/bvalidator/#groups

Related

Checking to see if a checkbox is selected before searching

I am having some trouble with my checkboxes. I am trying to get a returned true or false value out of event listeners on checkboxes and then passing it through an event listener on a button to confirm that at least one checkbox is selected. I'm sorry if this sounds confusing and I feel like there is an easier way to do this. I would like to solve this with pure JavaScript. Really appreciate the help. Below is the code.
<body>
<script src="racquetObjects.js"></script>
<div class="mainContainer">
<div class="selectors">
<form action="">
<div class="checkboxes">
<input type="checkbox" id="babolat" value="Babolat" />
<label for="babolat">Babolat</label>
<input type="checkbox" id="wilson" value="Wilson" />
<label for="wilson">Wilson</label>
<input type="checkbox" id="power" value="Power" />
<label for="power">Power</label>
<input type="checkbox" id="control" value="Control" />
<label for="control">Control</label>
<input type="checkbox" id="popular" value="Popular" />
<label for="popular">Popular</label>
</div>
<button type="button" id="find">Find</button>
</form>
</div>
<div class="racquetContainer"></div>
<div class="bench"></div>
</div>
<script src="racquetFinderCB.js"></script>
<script src="racquetFinder.js"></script>
</body>
const findButton = document.querySelector("#find");
const checkboxes = document.querySelectorAll(
".checkboxes input[type=checkbox]"
);
const checkboxesAreChecked = checkboxes.forEach((el) => {
el.addEventListener("click", (e) => {
if (e.target.checked) {
return true;
} else {
return false;
}
});
});
const beforeSubmit = () => {
if (checkboxesAreChecked === true) {
console.log("Time to search!");
} else {`enter code here`
console.log("You need to select an option");
}
};
In this example there is an event listener for the form submit. An array of the input elements is filtered, so only the checked will end up in checked.
The first e.preventDefault() is just for testing. If the form should submit (something was checked) then remove that line of code.
document.forms.find.addEventListener('submit', e => {
let inputs = e.target.querySelectorAll('input');
e.preventDefault(); // prevent default to test what happens
let checked = [...inputs].filter(input => input.checked);
if (checked.length > 0) {
console.log('at least one was checked');
} else {
e.preventDefault(); // prevent default to stop the form action
console.log('none was checked');
}
});
<div class="mainContainer">
<div class="selectors">
<form name="find" action="">
<div class="checkboxes">
<input type="checkbox" id="babolat" value="Babolat" />
<label for="babolat">Babolat</label>
<input type="checkbox" id="wilson" value="Wilson" />
<label for="wilson">Wilson</label>
<input type="checkbox" id="power" value="Power" />
<label for="power">Power</label>
<input type="checkbox" id="control" value="Control" />
<label for="control">Control</label>
<input type="checkbox" id="popular" value="Popular" />
<label for="popular">Popular</label>
</div>
<button id="find">Find</button>
</form>
</div>
<div class="racquetContainer"></div>
<div class="bench"></div>
</div>

Javascript quiz with multiple radio and text input types

I've made a small test/quiz with radio and checkbox types. Radio button in my code is mandatory to be checked and when it is, I get the total score for all correct answers, when it's not I get alert message that i need to check all questions.
Now I want to expand this quiz.
1st problem: I've made multiple radio type questions, I don't know how to check if all radio type questions are checked.
2nd problem: I've made test type questions and I want them to be seen after I push "Finish" (alongside total score from test questions), but when I push "Finish" I do not see the text type answers.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./CSS/reset.css">
<link rel="stylesheet" href="./CSS/main.css">
<title>Exam</title>
<script src="./JS/assessor.js"></script>
</head>
<body>
<section>
<main>
<h2>This is the exam</h2>
<form name="exam" id="exam">
<div class="question">
<div class="questionTitle">Question 1</div>
<p><input type="radio" id="answer1" name="answer1" value="wrong">wrong</p>
<p><input type="radio" id="answer1" name="answer1" value="wrong">wrong</p>
<p><input type="radio" id="answer1" name="answer1" value="wrong">wrong</p>
<p><input type="radio" id="answer1" name="answer1" value="right">right</p>
</div>
<div class="question">
<div class="questionTitle1">Question 1</div>
<p><input type="radio" id="answer3" name="answer3" value="wrong">wrong</p>
<p><input type="radio" id="answer3" name="answer3" value="wrong">wrong</p>
<p><input type="radio" id="answer3" name="answer3" value="wrong">wrong</p>
<p><input type="radio" id="answer3" name="answer3" value="right">right</p>
</div>
<div class="question">
<div class="questionTitle">Question 2</div>
<p><input type="checkbox" id="answer2wrong1" name="answer2_1" value="wrong">wrong</p>
<p><input type="checkbox" id="answer2right1" name="answer2_2" value="right">right</p>
<p><input type="checkbox" id="answer2right2" name="answer2_2" value="right">right</p>
<p><input type="checkbox" id="answer2wrong2" name="answer2_4" value="wrong">wrong</p>
</div>
<div>
<label for="fname">First field</label><br>
<input type="text" id="fname" name="fname" value="button1"><br>
<label for="fname">Second field</label><br>
<input type="text" id="fname" name="fname" value="button2"><br>
<label for="fname">Third field</label><br>
<input type="text" id="fname" name="fname" value="button3"><br>
</div>
<input type="button" id="button" name="" value="Finish" onclick="validate();assess()">
</form>
<p id="result"></p>
</main>
</section>
</body>
</html>
function validate() {
var valid = false;
var x = document.exam.answer1;
for(var i=0; i<x.length; i++) {
if (x[i].checked) {
valid= true;
break;
}
}
if(valid) {
assess();
}
else {
alert("All questions must be checked");
return false
}
function assess() {
var score=0;
var q1=document.exam.answer1.value;
var result=document.getElementById('result');
var exam=document.getElementById('exam');
if (q1=="right") {score++}
if (answer2right1.checked===true) {score += 0.5}
if (answer2right2.checked===true) {score += 0.5}
if (answer2wrong1.checked===true) {score -= 0.5}
if (answer2wrong2.checked===true) {score -= 0.5}
exam.style.display="none";
result.textContent=`${score}`;
}
}
Nobody replies to me so I try to figure it out myself. Yet I face problems.
1st example:
I get Success when i check 1st questions answer, but i need to check if all questions are checked, and I need to do it at once. In this code i can only check 1 question's status wether checked or not.
var mark = document.getElementsByTagName('input');
for (var i=0; i<mark.length; i++) {
if (mark[i].type == 'radio' && mark[i].name=="answer1" && mark[i].checked==true) {
alert("YES")
break;
}
}
2nd example:
In this code it doesnt recognize my ID at all and neither true or false work.
if(document.getElementById("answer1").checked==true) {
alert("Success");
}
else {
alert("All questions must be checked");
}
I figured it out myself. I added few lines where for checked answer in every question the "filledQuestion" score increases by 1. Then if "filledQuestion" score is equal to the number of questions, it passes, if not, it shows error message.
function validate() {
var mark = document.getElementsByTagName('input');
var filledQuestion = 0;
for (var i=0; i<mark.length; i++) {
if (mark[i].type == 'radio' && mark[i].name=="answerR1" && mark[i].checked==true) {
filledQuestion = filledQuestion + 1
}
else if (mark[i].type == 'radio' && mark[i].name=="answerR2" && mark[i].checked==true) {
filledQuestion = filledQuestion + 1
break;
}
}
if (filledQuestion == 2) {
assess();
showDiv();
}
else (alert("All questions must be checked"))
My second issue was due to my choice to use ( exam.style.display="none"; ) line. When i do not use it, the score is visible in the same page and therefore i can see all the changes after i submit the form.

Different groups of checkbox not working in jquery

I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.
<body>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee<br>
<input type="submit" id="__mainAnimals" />
<br><br><br><br><br><br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe<br>
<input type="checkbox" value="Tea" name="drinks" />Tea<br>
<input type="checkbox" value="Milk" name="drinks" />Milk<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha<br>
<input type="submit" id="__mainDrinks" />
</div>
<div id="__DIVresult"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#__mainAnimals').click(function () {
getSelectedCheckBoxes('animals');
});
$('#__mainDrinks').click(function () {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function (groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function () {
resultString += $(this).val() + "<br/>";
});
$('__DIVresult').html(resultString);
}
else {
$('__DIVresult').html("No checkbox checked");
}
};
});
</script>
</body>
1st id selector is # so $('__DIVresult') should be $('#__DIVresult')
2nd An ID should start with a letter for compatibility
Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
REF: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id
3rd some small update, added two result div, one for animal one for drink:
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
Then target them dynamically with $('#DIVresult'+groupName).html(resultString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion
<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger
<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant
<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee
<br>
<input type="submit" id="mainAnimals" />
<br>
<br>
<br>
<br>
<br>
<br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe
<br>
<input type="checkbox" value="Tea" name="drinks" />Tea
<br>
<input type="checkbox" value="Milk" name="drinks" />Milk
<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha
<br>
<input type="submit" id="mainDrinks" />
</div>
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#mainAnimals').click(function() {
getSelectedCheckBoxes('animals');
});
$('#mainDrinks').click(function() {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function(groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function() {
resultString += $(this).val() + "<br/>";
});
$('#DIVresult'+groupName).html(resultString);
} else {
$('#DIVresult'+groupName).html("No checkbox checked");
}
};
});
</script>
In your drink and animal section you are not separating the two so when you use your click function it doesn't discriminate between the tow sections. Once you add each one to a class then the button will only call the checked items that are actually checked.
<html>
<form>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Lion" />Lion</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Tiger" />Tiger</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Elephant" />Elephant</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Girafee" />Girafee</br>
<input type="button" id="save_value" name="save_value" value="Save" /></br>
<textarea id="t"></textarea>
</form>
<script>
function updateTextArea() {
var allVals = [];
$('.ads_Checkbox:checked').each(function() {
allVals.push($(this).val());
});
$('#t').val(allVals);
}
$('#save_value').click(function(){
$('.ads_Checkbox:checked').each(function(){
updateTextArea();
});
});
Inside this code I have named each animal and placed them in a class so I could recall them from an array. I hoped this helped.

jQuery: How to uncheck random checkboxes in div after checking all?

When onClick on link occurs, all checkboxes present in that div are checked.
function initSelectAll() {
$("form").find("a.selectAll").click(function() {
var cb = $(this).closest("div").find("input[type=checkbox]");
cb.not(":checked").click().length || cb.click();
//........WANT TO UNCHECK checkboxes with class="file" where link id is 'id="ninapaya"'; how to do that?......
return false;
});
}
initSelectAll();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div>
Select
<span class="kukapaya">(alle)</span>
<br>
<input type="checkbox" class="document" name="check2">
<input type="checkbox" class="document" name="check2">
<br>
<input type="checkbox" class="File">
<input type="checkbox" class="File">
</div>
</form>
Requirement: We should not check the checkboxes with class="File".
JSFiddle: https://jsfiddle.net/k4d6zpay/
It could be simplified using .prop(.prop( propertyName, function )) and using :not selector
$("form").find("a.selectAll").click(function() {
$(this).closest("div").find("input[type='checkbox']:not('.File')").prop('checked', function() {
return !this.checked;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
<div>
Select
<span class="kukapaya">(alle)</span>
<br>
<input type="checkbox" class="document" name="check2">
<input type="checkbox" class="document" name="check2">
<br>
<input type="checkbox" class="File">
<input type="checkbox" class="File">
</div>
</form>
try this:
function initSelectAll() {
$("form").find("a.selectAll").click(function() {
var cb = $(this).closest("div").find("input[type=checkbox]");
cb.not(":checked").not('.File').click().length || cb.click();
return false;
});
}
initSelectAll();
Also update in your jsfiddle link: https://jsfiddle.net/k4d6zpay/1/
function initSelectAll() {
$("form").find("a.selectAll").click(function() {
var cb = $(this).closest("div").find("input[type=checkbox]:not(.File)");
cb.not(":checked").click().length || cb.click();
//........WANT TO UNCHECK checkboxes with class="file" where link id is 'id="ninapaya"';
$(this).closest("div").find("input[type=checkbox][id='ninapaya'].File").prop('checked',false);
return false;
});
}
initSelectAll();

Check all checkboxes with JavaScript

I want to have the first checkbox that allows me to check or uncheck all of the other boxes. Here is the code I am using:
<html>
<head>
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsById('checkall');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
</head>
<body>
<input type='checkbox' onClick='toggle(this)' /><br />
<input type='checkbox' id='checkall' name='orders[0][order_id]' value='16885' /><br />
<input type='checkbox' id='checkall' name='orders[1][order_id]' value='17006' /><br />
<input type='checkbox' id='checkall' name='orders[2][order_id]' value='17006' /><br />
<input type='checkbox' id='checkall' name='orders[3][order_id]' value='17007' /><br />
<input type='checkbox' id='checkall' name='orders[4][order_id]' value='17011' /><br />
</body>
</html>
This has worked for me.
function toggle(oInput) {
var aInputs = document.getElementsByTagName('input');
for (var i=0;i<aInputs.length;i++) {
if (aInputs[i] != oInput) {
aInputs[i].checked = oInput.checked;
}
}
}
Though, if you want to limit this to only certain checkboxes, add a classname to them, and to the master checkbox
<html>
<head>
<script type="text/javascript">
function toggle(source) {
var aInputs = document.getElementsByTagName('input');
for (var i=0;i<aInputs.length;i++) {
if (aInputs[i] != source && aInputs[i].className == source.className) {
aInputs[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<input type='checkbox' class='checkall' onClick='toggle(this)' /><br />
<input type='checkbox' class='checkall' name='orders[0][order_id]' value='16885' /><br />
<input type='checkbox' class='checkall' name='orders[1][order_id]' value='17006' /><br />
<input type='checkbox' class='checkall' name='orders[2][order_id]' value='17006' /><br />
<input type='checkbox' class='checkall' name='orders[3][order_id]' value='17007' /><br />
<input type='checkbox' class='checkall' name='orders[4][order_id]' value='17011' /><br />
</body>
</html>
The problem is you are using the same id for all the checkbox groups. An id must be unique to a page. Instead you may use the checkbox name. Since the names have [] with varying values, you can use indexOf to examine just the first part.
<html>
<head>
<script language="JavaScript">
function toggle(source) {
// Get all input elements
var inputs = document.getElementsByTagName('input');
// Loop over inputs to find the checkboxes whose name starts with `orders`
for(var i =0; i<inputs.length; i++) {
if (inputs[i].type == 'checkbox' && inputs[i].name.indexOf('orders') === 0) {
inputs[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<input type='checkbox' onClick='toggle(this)' /><br />
<input type='checkbox' id='checkall' name='orders[0][order_id]' value='16885' /><br />
<input type='checkbox' id='checkall' name='orders[1][order_id]' value='17006' /><br />
<input type='checkbox' id='checkall' name='orders[2][order_id]' value='17006' /><br />
<input type='checkbox' id='checkall' name='orders[3][order_id]' value='17007' /><br />
<input type='checkbox' id='checkall' name='orders[4][order_id]' value='17011' /><br />
</body>
</html>
Try this...
<form id="form_">
<input type='checkbox' name='item1' value='16885' />
<input type='checkbox' name='item1' value='17006' />
<input type='checkbox' name='item1' value='17006' />
<input type='checkbox' name='item1' value='17007' />
<input type='checkbox' name='item1' value='17011' />
<br/>Select All
<br/>Clear All
<button id="btnRemove1"><br/>Remove</button>
</form>
<script>
$("#select_all1").click(function() {
var item = document.getElementsByName("item1");
for (var i=0; i < item.length; i++) {
item[i].setAttribute("checked");
}
});
$("#clear_all1").click(function() {
var item = document.getElementsByName("item1");
for (var i=0; i < item.length; i++) {
if(item[i].checked) {
item[i].removeAttribute("checked");
} else {
alert("Nothing to clear.");
return false;
}
}
});
$("#btnRemove1").click(function() {
var items = $('.item1').is(':checked');
if(items) {
window.location = "/contents?"+ $("form#form_").serialize();
}
else {
alert("Nothing to remove.");
return false;
}
});
</script>
It's better to use the querySelectorAll. here is the example.
The Html with checkboxes
<input type="button" value="Select All" onclick="selectAll()" id="TestAll" />
<input type='checkbox' id='checkAll' name='Test1' />
<input type='checkbox' id='checkall' name='Test2' />
<input type='checkbox' id='checkAll' name='Test3' />
<input type='checkbox' id='checkAll' name='Test4' />
<input type='checkbox' id='checkAll' name='Test5' />
Here is the javascript for this
function selectAll() {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox')
checkboxes[i].checked = true;
}
}
IDs are supposed to be unique - never have more than one HTML element with the same id, it's invalid. That's also why you have a problem - there is no such method as document.getElementsById, only document.getElementById. Instead, you could use classes. Here's how to solve your problem in pure JavaScript:
function toggle(source) {
var inputs = document.getElementsByTagName('input');
var i, input;
for(i = 0; input = inputs[i]; i++) {
if((' ' + input.className + ' ').indexOf(' checkall ') > -1) {
input.checked = source.checked;
}
}
}
And change all your id="checkall"s to class="checkall".
Or you could use jQuery. It's great and does all things ;)
You can simply wrap all checkboxes that you nead itterate throu into the DIV and access to it's childNodes and use getElementById to access that DIV
<head>
<script language="JavaScript">
function toggle(source) {
//use getElementById to access to DOM objects by ID
var checkboxes = document.getElementById('checkall').childNodes;
var source = document.getElementById('source');
//now just itterate throu all checkboxess that is in the 'checkall' DIV
for(var i in checkboxes) {
checkboxes[i].checked = source.checked;
}
}
</script>
</head>
<body>
<!--Give an ID to the source checkbox so we could access it from Javascript-->
<input id="source" type='checkbox' onClick='toggle(this)' /><br />
<!--Just wrap all checkboxes that you nead to itterate into the DIV-->
<div id="checkall">
<input type='checkbox' name='orders[0][order_id]' value='16885' /><br />
<input type='checkbox' name='orders[1][order_id]' value='17006' /><br />
<input type='checkbox' name='orders[2][order_id]' value='17006' /><br />
<input type='checkbox' name='orders[3][order_id]' value='17007' /><br />
<input type='checkbox' name='orders[4][order_id]' value='17011' /><br />
</div>
</body>
</html>

Categories