Simple quiz issue - javascript

I'm trying to build a basic one question quiz. Based on the checkboxes checked 1 of 3 result divs should show.
If consolidation hasn’t been checked then it should show the low results div
If everything has been checked then show the high results div
If consolidation has been ticked but other items are unticked then show medium results div
I also need to populate the medium results div with the names of the boxes that weren't checked on submit but I don't know how to go about it. Right now I've got it mostly working on submit but I can only get medium and low results to show, not the high results div. I think it's an issue with the priorities of the statements.
https://jsfiddle.net/lucym/azLf2s0t/3/
var a = document.querySelector('#consolidation');
var btn = document.querySelector('#btn')
btn.onclick = () => {
if (a.checked == false) {
$('#low').show();
} else if ($('#list :checkbox:not(checked)').length == 0) {
$('#high').show();
} else if (a.checked == true) {
$('#medium').show();
} else {
alert('select an option');
}
};
.results {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list" style="max-width: 650px; margin: 40px auto;">
<!-- Consolidatation-->
<fieldset>
<input id="consolidation" type="checkbox" name="">
<label>Searched and combined lost funds</label>
</fieldset>
<!-- Advice -->
<fieldset>
<input id="advice" type="checkbox" name="">
<label>Talked with an advisor</label>
</fieldset>
<!-- identity -->
<fieldset>
<input id="identity" type="checkbox" name="">
<label>Completed an ID check</label>
</fieldset>
<!-- balance -->
<fieldset>
<input id="balance" type="checkbox" name="">
<label>Checked your balance</label>
</fieldset>
<!-- app -->
<fieldset>
<input id="app" type="checkbox" name="">
<label>Downloaded the Sunsuper app</label>
</fieldset>
<!-- calculator -->
<fieldset>
<input id="calculator" type="checkbox" name="">
<label>Used our retirement calculator</label>
</fieldset>
<!-- SUBMIT BUTTON -->
<input type="button" id="btn" value="Submit">
<!-- Result options -->
<div id="low" class="results">low results</div>
<div id="medium" class="results">medium results</div>
<div id="high" class="results">high results</div>
</div>

You missed : before checked ($('#list :checkbox:not(:checked)').length == 0):
var a = document.querySelector('#consolidation');
var btn = document.querySelector('#btn')
btn.onclick = () => {
if (a.checked == false) {
$('#low').show();
$('#high').hide();
$('#medium').hide();
} else if ($('#list :checkbox:not(:checked)').length == 0) {
$('#high').show();
$('#medium').hide();
$('#low').hide();
} else if (a.checked == true) {
mytext='<br> You have an average results, try doing :<br>';
var unchecked = $('#list :checkbox:not(:checked)');
for (i = 0; i < unchecked.length-1; i++)
mytext +=unchecked[i].nextSibling.nextSibling.innerText+', ';
mytext+=unchecked[unchecked.length-1].nextSibling.nextSibling.innerText;
mytext+=' to improve.';
$('#medium').append(mytext);
$('#medium').show();
} else {
alert('select an option');
}
};
.results {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list" style="max-width: 650px; margin: 40px auto;">
<!-- Consolidatation-->
<fieldset>
<input id="consolidation" type="checkbox" name="">
<label>Searched and combined lost funds</label>
</fieldset>
<!-- Advice -->
<fieldset>
<input id="advice" type="checkbox" name="">
<label>Talked with an advisor</label>
</fieldset>
<!-- identity -->
<fieldset>
<input id="identity" type="checkbox" name="">
<label>Completed an ID check</label>
</fieldset>
<!-- balance -->
<fieldset>
<input id="balance" type="checkbox" name="">
<label>Checked your balance</label>
</fieldset>
<!-- app -->
<fieldset>
<input id="app" type="checkbox" name="">
<label>Downloaded the Sunsuper app</label>
</fieldset>
<!-- calculator -->
<fieldset>
<input id="calculator" type="checkbox" name="">
<label>Used our retirement calculator</label>
</fieldset>
<!-- SUBMIT BUTTON -->
<input type="button" id="btn" value="Submit">
<!-- Result options -->
<div id="low" class="results">low results</div>
<div id="medium" class="results">medium results</div>
<div id="high" class="results">high results</div>
</div>

Related

If I select a checkbox, I deactivate another

Update 10/21/2021 - I still need a resolution.
Here's the situation: As you can see in the visual example below. I have four - buttons radio - I need to make an event where when I select the option "NO" of the compo I automatically disable the two selections in the field .
If "YES" is selected, the two other selections must remain active. My problem is because the four stamps are "radio buttons" and not a checkbox.
Visual example:
<-- IVF fertilization -->
⬜ Yes
⬜ No
<-- if IVF ovum -->
⬜ Own
⬜ From a donor
And the third code is the HTML part, for analysis.
I have this snippet:
Code 1
Base PHP code I'm using.
<!-- IVF fertilization -->
<div class='col-sm-4'>
<?=_('IVF fertilization')?>
<div>
<input type="radio" id="yesFe" name="niptData_ivfFertilization" value='1'
<?=($_SESSION['REQUEST']['niptData_ivfFertilization-required0allow'] == '1' OR $registration->test->data->ivfFertilization == '1') ? 'checked' : ''?>
>
<label for="yesFe" class='smallLabel'><?=_('Yes')?></label>
</div>
<div>
<input type="radio" id="noFe" name="niptData_ivfFertilization" value='0'
<?=($_SESSION['REQUEST']['niptData_ivfFertilization-required0allow'] == '0' OR $registration->test->data->ivfFertilization == '0') ? 'checked' : ''?>
>
<label for="noFe" class='smallLabel'><?=_('No')?></label>
</div>
</div>
<!-- if IVF ovum -->
<div class='col-sm-4'>
<?=_('If IVF ovum')?>
<div>
<input type="radio" id="ownOv" name="niptData_ovum" value='1' data-validation=""
<?=($_SESSION['OPTIONAL']['niptData_ovum'] == '1' OR $registration->test->data->ovum == '1') ? 'checked' : ''?>
>
<label for="ownOv" class='smallLabel'><?=_('Own')?></label>
</div>
<div>
<input type="radio" id="fromADonor" name="niptData_ovum" value='2' data-validation=""
<?=($_SESSION['OPTIONAL']['niptData_ovum'] == '2' OR $registration->test->data->ovum == '2') ? 'checked' : ''?>
>
<label for="fromADonor" class='smallLabel'><?=_('From a donor')?></label>
</div>
<br>
</div>
CODE 2
Script that working to solve the problem.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('#new_user_form *').filter(':radio').change(function() {
if(this.id=='noFe' && this.value=='0' && $(this).is(':checked')) {
$('#new_user_form *').filter(':radio').each(function(){
if(this.id=='noFe' && this.value=='0') {
} else {
$(this).attr("checked",false);
}
});
}
if((this.id=='ownOv' || this.id=='fromADonor' && this.value=='0') {
var checkedId = this.id;
var checkedOrNot = $(this).is(':checked');
$('#new_user_form *').filter(':radio').each(function(){
if(this.id==checkedId && (this.value=='1' || this.value=='2')) {
if(checkedOrNot) {
$(this).attr("disabled",true);
} else {
$(this).attr("disabled",false);
}
}
});
</script>
CODE 3
HTML code that was asked of me.
<div class="col-sm-4">
Pregnancy<span class="required">*</span>
<div class="has-error">
<input type="radio" id="yesFe" name="niptData_ivfFertilization-required0allow" value="1" data-validation="required" class="error" style="border-color: rgb(185, 74, 72);">
<label for="yesFe" class="smallLabel">Yes</label>
<span class="help-block form-error">Required field</span></div>
<div class="has-success">
<input type="radio" id="noFe" name="niptData_ivfFertilization-required0allow" value="0" data-validation="required" class="valid" style="">
<label for="noFe" class="smallLabel">No</label>
</div>
</div>
<div class="col-sm-4">
if FIVET, ovum<span class="optional"></span>
<div>
<input type="radio" id="ownOv" name="niptData_ovum" value="1" data-validation="">
<label for="ownOv" class="smallLabel">Own</label>
</div>
<div>
<input type="radio" id="fromADonor" name="niptData_ovum" value="2" data-validation="">
<label for="fromADonor" class="smallLabel">
As a donor</label>
</div>
<br>
</div>
I dont know if I understand right but here is solution:
1- I deleted the codes that not inportant for that issue
2- I added class name "secondis" to elements that I will disable after checkbox clicked
Hope you got what you wanted
$("#yesFe").click(function(){
if ($(this).prop("checked") == true) {$("#secondissue").show();$(".secondis").prop('disabled', false);}
else {$("#secondissue").hide();$(".secondis").prop('disabled', true);}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-4">
Pregnancy<span class="required">*</span>
<div class="has-error">
<input type="checkbox" id="yesFe" name="niptData_ivfFertilization-required0allow" value="1" data-validation="required" class="error " style="border-color: rgb(185, 74, 72);">
<label for="yesFe" class="smallLabel">Sì</label>
<span class="help-block form-error">Required field</span></div>
<div class="has-success">
<input type="checkbox" id="noFe" name="niptData_ivfFertilization-required0allow" value="0" data-validation="required" class="valid" style="">
<label for="noFe" class="smallLabel">No</label>
</div>
</div>
<div class="col-sm-4" id ="secondissue" style="display:none">
Se FIVET, ovuli<span class="optional"></span>
<div>
<input type="radio" id="ownOv" name="niptData_ovum" value="1" class="secondis" data-validation="" >
<label for="ownOv" class="smallLabel">Propri</label>
</div>
<div>
<input type="radio" id="fromADonor" name="niptData_ovum" class="secondis" value="2" data-validation="" >
<label for="fromADonor" class="smallLabel">Da donatrice</label>
</div>
<br>
</div>

How to use querySelectorAll to disable a button if all radios in a div have not been checked?

I have the following page which I would like to force the user to check all the radios in the first view:
function show(shown, hidden) {
document.getElementById(shown).style.display = 'block';
document.getElementById(hidden).style.display = 'none';
document.querySelector('[data-testid="crowd-submit"]').style.display = 'inline-block';
return false;
}
function enableButton() {
if (document.querySelectorAll("link[type^=radio]:checked") !== null) {
document.getElementById('button').disabled = false;
}
}
[data-testid="crowd-submit"] {
display: none;
}
<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>
<crowd-form answer-format="flatten-objects">
<!-- Start Page number one (part 1) -->
<div id="Page1">
<h2>Part 1/2</h2>
<div class="container">
<h4> this is question 1?</h4>
<input type="radio" value="val1" name="question1_1" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question1_1" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question1_1" required onclick="enableButton()">C</input>
<i></i>
</div>
<div class="container">
<h4> this is question 2?</h4>
<input type="radio" value="val1" name="question2_2" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question2_2" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question2_2" required onclick="enableButton()">C</input>
<i></i>
</div>
<button type="button" id="button" class="d-block mr-0 ml-auto" disabled onclick="return show('Page2','Page1');"><b>Next</b></button>
<br>
<br>
</div>
<!-- End Page number one (part 1) -->
<!-- start Page number two (part 2) -->
<div id="Page2" style="display:none">
<h2>Part 2/2</h2>
<div class="container">
<h4> this is question 2?</h4>
<input type="radio" value="val1" name="question3_3" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question3_3" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question3_3" required onclick="enableButton()">C</input>
<i></i>
</div>
</div>
</crowd-form>
How can I disable the next button, until all the radios in the first view have not been answered?
So far, what I tried was:
document.querySelectorAll("link[type^=radio]:checked") !== null
And
if (document.querySelectorAll("link[type^=radio]:checked").length !== null) {
document.getElementById('button').disabled = false;
}
}
And with Jquery:
$(function(){
$("input[type='radio']").change(function(){
$("input[type='submit']").prop("disabled", false);
});
});
However, these attemps have not worked, because if you answer only one set of radios in the first view, the website allows you to continue with the second one. How can I disable the next button, until all the checkboxes in the first view have been completed?
What is even link in link[type^=radio]?
its input[type^=radio]
Also if you are checking .length you need to compare it to an number not null...
.length Always returns an number, 0 >
.length !== 0
function show(shown, hidden) {
document.getElementById(shown).style.display = 'block';
document.getElementById(hidden).style.display = 'none';
document.querySelector('[data-testid="crowd-submit"]').style.display = 'inline-block';
return false;
}
function enableButton() {
console.log(document.querySelectorAll("input[type^=radio][name=question1_1]:checked").length)
console.log(document.querySelectorAll("input[type^=radio][name=question1_2]:checked").length)
if (document.querySelectorAll("input[type^=radio][name=question1_1]:checked").length !== 0 && document.querySelectorAll("input[type^=radio][name=question2_2]:checked").length !== 0) {
document.getElementById('button').disabled = false;
}
}
[data-testid="crowd-submit"] {
display: none;
}
<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>
<crowd-form answer-format="flatten-objects">
<!-- Start Page number one (part 1) -->
<div id="Page1">
<h2>Part 1/2</h2>
<div class="container">
<h4> this is question 1?</h4>
<input type="radio" value="val1" name="question1_1" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question1_1" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question1_1" required onclick="enableButton()">C</input>
<i></i>
</div>
<div class="container">
<h4> this is question 2?</h4>
<input type="radio" value="val1" name="question2_2" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question2_2" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question2_2" required onclick="enableButton()">C</input>
<i></i>
</div>
<button type="button" id="button" class="d-block mr-0 ml-auto" disabled onclick="return show('Page2','Page1');"><b>Next</b></button>
<br>
<br>
</div>
<!-- End Page number one (part 1) -->
<!-- start Page number two (part 2) -->
<div id="Page2" style="display:none">
<h2>Part 2/2</h2>
<div class="container">
<h4> this is question 2?</h4>
<input type="radio" value="val1" name="question3_3" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question3_3" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question3_3" required onclick="enableButton()">C</input>
<i></i>
</div>
</div>
</crowd-form>
If you want to use 0 as compression just use more direct CSS targeting and add one more condition:
if (document.querySelectorAll("input[type^=radio][name=question1_1]:checked").length !== 0 && document.querySelectorAll("input[type^=radio][name=question2_2]:checked").length !== 0)
so you can put in those two groups any number of options, and in each at least one needs to be picked.
You need to check for the number of radio buttons that are checked, right now you are just checking if any radio buttons are checked.
function enableButton() {
// check if both radio buttons are checked
if (document.querySelectorAll("link[type^=radio]:checked").length == 2) {
document.getElementById('button').disabled = false;
}
}

Javascript conditionals not working on correct button combination

I have 5 if else conditions under function getRadioButtonValue. The function does not go through all the conditions even after clicking the right button combinations.
I have tried to debug the script using Chrome Developer tools but the problem still exists. Where is the code breaking?
Some information regarding the page, I am using Javascript to hide the div's and headers so that at any one time there is only one question seen.
Only the first if conditions work, but nothing else
The results are seen after Get Result button is clicked on the last page which should redirect to the appropriate page.
[DELETED CODE]
[UPDATED CODE]
I am unable to auto hide my div's based on the response given below by Keith.
FYI: His code works as expected.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.hidden {
display: none;
}
.visible {
display: block;
margin: 0 auto;
width: 650px;
height: 445px;
background: #EFDFBC;
}
</style>
</head>
<body>
<div id="first-question" class="visible">
<h3>How?</h3>
<ul>
<li>abc</li>
<li>def</li>
</ul>
<hr>
<input type="radio" name="quiz-question-one" id="quiz-question-one-yes" value="yes" />
<label for="quiz-question-one-yes" id="oneYes">Yes</label>
<input type="radio" name="quiz-question-one" id="quiz-question-one-no" value="no" />
<label for="quiz-question-one-no" id="oneNo">No</label>
</div>
<div id="second-question" class="hidden">
<h3>To</h3>
<hr>
<input type="radio" name="quiz-question-two" id="quiz-question-two-yes" value="yes" />
<label for="quiz-question-two-yes" id="twoYes">Yes</label>
<input type="radio" name="quiz-question-two" id="quiz-question-two-no" value="no" />
<label for="quiz-question-two-yes" id="twoNo">No</label>
</div>
<div id="third-question" class="hidden">
<h3>Make </h3>
<hr>
<input type="radio" name="quiz-question-three" id="quiz-question-three-yes" value="yes" />
<label for="quiz-question-three-yes" id="threeYes">Yes</label>
<input type="radio" name="quiz-question-three" id="quiz-question-three-no" value="no" />
<label for="quiz-question-three-yes" id="threeNo">No</label>
</div>
<div id="fourth-question" class="hidden">
<h3>This</h3>
<hr>
<input type="radio" name="quiz-question-four" id="quiz-question-four-yes" value="yes" />
<label for="quiz-question-four-yes" id="fourYes">Yes</label>
<input type="radio" name="quiz-question-four" id="quiz-question-four-no" value="no" />
<label for="quiz-question-four-yes" id="fourNo">No</label>
</div>
<div id="fifth-question" class="hidden">
<h3>Work?</h3>
<hr>
<input type="radio" name="quiz-question-five-yes" id="quiz-question-five-yes" value="yes" />
<label for="quiz-question-five-yes" id="fiveYes">Yes</label>
<input type="radio" name="quiz-question-five-no" id="quiz-question-five-no" value="no" />
<label for="quiz-question-five-yes" id="fiveNo">No</label>
</div>
<div class="page result">
<label>Results</label>
<div id="result"></div>
</div>
</body>
</html>
<script type="text/javascript">
var results = {};
function updateResult() {
var r = results,
rt = $('#result');
if (r.quiz-question-one && r.quiz-question-two && r.quiz-question-three && r.quiz-question-four && r.quiz-question-five) {
rt.text('All Yes');
} else if (!r.quiz-question-one && !r.quiz-question-two && !r.quiz-question-three && !r.quiz-question-four && !r.quiz-question-five) {
rt.text('All No');
} else {
rt.text('We have a mixed response');
}
}
$(function () {
$('body').on('click', '[name]', function () {
var $this = $(this),
page = $this.closest('.hidden'),
next_page = $(page.next());
results[$this.attr('name')] = $(this).val() === 'yes';
page.removeClass('visible');
next_page.addClass('visible');
if (next_page.hasClass('result')) updateResult();
});
});
</script>
I've created an example below that I think you can work from. The values from the radio I don't think get updated until you submit, instead I've captured the results in the onclick. You can now add back you CSS styling etc. Hope that helps.
var results = {};
function updateResult() {
var r = results,
rt = $('#result');
if (r.q1 && r.q2 && r.q3) {
rt.text('All Yes');
} else if (!r.q1 && !r.q2 && !r.q3) {
rt.text('All No');
} else {
rt.text('We have a mixed response');
}
}
$(function () {
$('body').on('click', '[name]', function () {
var $this = $(this),
page = $this.closest('.page'),
next_page = $(page.next());
results[$this.attr('name')] = $(this).val() === 'yes';
page.removeClass('active');
next_page.addClass('active');
if (next_page.hasClass('result')) updateResult();
});
});
.page {
display: none;
}
.page.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page active">
<div>Question 1</div>
<label for="q1yes">Yes</label>
<input id="q1yes" type="radio" name="q1" value="yes">
<label for="q1no">No</label>
<input id="q1no" type="radio" name="q1" value="no">
</div>
<div class="page">
<div>Question 2</div>
<label for="q2yes">Yes</label>
<input id="q2yes" type="radio" name="q2" value="yes">
<label for="q2no">No</label>
<input id="q2no" type="radio" name="q2" value="no">
</div>
<div class="page">
<div>Question 3</div>
<label for="q3yes">Yes</label>
<input id="q3yes" type="radio" name="q3" value="yes">
<label for="q3no">No</label>
<input id="q3no" type="radio" name="q3" value="no">
</div>
<div class="page result">
<label>Results</label>
<div id="result"></div>
</div>
<input type="radio" id="quiz-question-one-yes" value="yes" />
<label for="quiz-question-one-yes" id="oneYes">Yes</label>
<input type="radio" id="quiz-question-one-no" value="no" />
<label for="quiz-question-one-no" id="oneNo">No</label>
In the above you are using type="radio", that means all type="radio" with the same name will group together, and not just these two. To group together just give them a name on the input. eg.
<input type="radio" name="quiz-question-one" id="quiz-question-one-yes" value="yes" />
<label for="quiz-question-one-yes" id="oneYes">Yes</label>
<input type="radio" name="quiz-question-one" id="quiz-question-one-no" value="no" />
<label for="quiz-question-one-no" id="oneNo">No</label>
Above you can see I've given the 2 inputs the name="quiz-question-one", and then for the next question maybe give them a name="quiz-question-two" etc..
On another note, there are lots of places where your code could be simplified, but hopefully this will solve your current problem.

how to dynamically change theme of JQM collapsible

I have this collapsible:
<div id ="optionsDiv" data-role="collapsible" data-collapsed-icon="gear" data-expanded-icon="gear" data-collapsed="false" data-theme="b" data-content-theme="c">
<h3>Options</h3>
<div data-role="fieldcontain" id="checkboxesDiv">
<label>
<input type="checkbox" name="clearafter" id="cbClearAfter" />Clear After Solving</label>
<label>
<input type="checkbox" name="alwayssimplify" id="alwaysSimplify" />Always Simplify Roots (may be wrong)</label>
<small id="whatsthatinfobox">What's This?</small>
<hr>
<fieldset data-role="controlgroup" data-type="horizontal" id="themeChanger">
<legend>Theme:</legend>
<input type="radio" name="radio-choice" id="radio-choice-day" value="day" checked="checked" />
<label for="radio-choice-day">Day</label>
<input type="radio" name="radio-choice" id="radio-choice-night" value="night" />
<label for="radio-choice-night">Night</label>
</fieldset>
</div>
</div>
This detects changes between the horizontal radio buttons:
$("#themeChanger").change(function(){
if ($("#radio-choice-day").is(":checked"))
{
theme = "day";
}
else
{
theme = "night";
}
changeTheme(theme);
});
What would you put here:
function changeTheme(theme)
{
if (theme=="day")
{
//change to day theme
}
else
{
//change to night theme
}
}
In order to change the data-theme and the data-content-theme attributes of the collapsible?
I have tried using attr("data-theme","a"); but it does not work.
Thank you.
You just need to call the Collapsible Widget with other options.
$("#optionsDiv").collapsible({theme: "a", contentTheme: "a"});
$("#optionsDiv").collapsible({theme: "b", contentTheme: "b"});
$("#themeChanger").change(function() {
if ($("#radio-choice-day").is(":checked")) {
theme = "day";
} else {
theme = "night";
}
changeTheme(theme);
});
function changeTheme(theme) {
if (theme == "day") {
$("#optionsDiv").collapsible({
theme: "a",
contentTheme: "a"
});
} else {
$("#optionsDiv").collapsible({
theme: "b",
contentTheme: "b"
});
}
}
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- jQuery Mobile -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<div id="optionsDiv" data-role="collapsible" data-collapsed-icon="gear" data-expanded-icon="gear" data-collapsed="false" data-theme="b" data-content-theme="c">
<h3>Options</h3>
<div data-role="fieldcontain" id="checkboxesDiv">
<label>
<input type="checkbox" name="clearafter" id="cbClearAfter" />Clear After Solving</label>
<label>
<input type="checkbox" name="alwayssimplify" id="alwaysSimplify" />Always Simplify Roots (may be wrong)</label>
<small id="whatsthatinfobox">What's This?</small>
<hr>
<fieldset data-role="controlgroup" data-type="horizontal" id="themeChanger">
<legend>Theme:</legend>
<input type="radio" name="radio-choice" id="radio-choice-day" value="day" checked="checked" />
<label for="radio-choice-day">Day</label>
<input type="radio" name="radio-choice" id="radio-choice-night" value="night" />
<label for="radio-choice-night">Night</label>
</fieldset>
</div>
</div>

Javascript, flask, making sure at least one checkbox from each "type" is selected

I have a flask template that loads a form in a modal window for me. The form has 3 drop downs which work well with the required attribute, but it also has two "sets" of checkboxes. Within each set the user must pick one. I am new to javascript and can't seem to get anything to work. The days and actions have to have separate ids in order for the css to work properly with the special checkboxes we have. How can my users be forced to select one action and one day?
EDIT
Yes, the goal is for someone to be able to check multiple days, or both values for the two actions. I am pretty terrible with css, so if someone has a way to accomplish this with multiple classes then I can certainly make edits.
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" language="JavaScript">
function checkCheckBoxes(theForm) {
if (
theForm.m.checked == false &&
theForm.t.checked == false &&
theForm.w.checked == false &&
theForm.th.checked == false &&
theForm.f.checked == false &&
theForm.s.checked == false &&
theForm.sn.checked == false &&)
{
alert ('You didn\'t choose a day!');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div class="box" title="Schedule">
<div class="wrapper">
<a data-popup="On demand" href="#refresh" value="Refresh Now">Refresh Now</a>
</div>
Change Schedule
</div>
<aside class="modal" id="schedule">
<h2 >Refresh Schedule</h2>
<section >
<div class="onoffswitch">
<form name="onoff" method="post" action="{{ url_for('togglebool') }}">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="onoffswitch" onchange="this.form.submit()" {{ checkval }}>
<label class="onoffswitch-label" for="onoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</form>
</div>
<p id="schedule-mssg"><strong>When should this occur?</strong></p>
<form method='POST' name="schedule_time" action="{{ url_for('info') }}" onsubmit="return checkCheckBoxes(this);">
<select class="custom-dropdown" name="hour" id="hour" required>
<option value="" selected disabled>Hour</option>
{% for i in hours %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
<select class="custom-dropdown" name="minute" id="minute" required>
<option value="" selected disabled>Minute</option>
{% for i in minutes %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
<select class="custom-dropdown" name="period" id="period" required>
<option value="" selected disabled>AM/PM</option>
<option>AM</option>
<option>PM</option>
</select>
<!--Actions, at least one must be checked-->
<input type="checkbox" name="action" id="code" class="css-checkbox" value="code" checked><label for="code" class="css-label">Code</label>
<input type="checkbox" name="action" id="database" class="css-checkbox" value="database" checked><label for="database" class="css-label">Database</label>
<div id="schedule-form">
> <!--Days, at least one must be checked in addition to at least one action-->
<input type="checkbox" name="m" id="m" class="css-checkbox" value="1" checked><label for="m" class="css-label">Mon</label>
<input type="checkbox" name="t" id="t" class="css-checkbox" value="2" checked><label for="t" class="css-label">Tues</label>
<input type="checkbox" name="w" id="w" class="css-checkbox" value="3" checked><label for="w" class="css-label">Wed</label>
<input type="checkbox" name="th" id="th" class="css-checkbox" value="4" checked><label for="th" class="css-label">Thur</label>
<input type="checkbox" name="f" id="f" class="css-checkbox" value="5" checked><label for="f" class="css-label">Fri</label>
<input type="checkbox" name="s" id="s" class="css-checkbox" value="6" checked><label for="s" class="css-label">Sat</label>
<input type="checkbox" name="sn" id="sn" class="css-checkbox" value="7" checked><label for="sn" class="css-label">Sun</label>
</fieldset>
</div>
<input type="submit" name="sched-sub" id="schedule-sub" value="Save Changes"; />
Close
</form>
</section>
<footer class="cf">
</footer>
</section>
</aside>
</body>
CSS for checkboxes
/* Begin Checkboxes */
input[type=checkbox].css-checkbox {
position:absolute;
z-index:-1000;
left:-1000px;
overflow: hidden;
clip: rect(0 0 0 0);
height:1px;
width:1px;
margin:-1px;
padding:0;
border:0;
}
input[type="checkbox"].css-checkbox + label.css-label { padding-left: 27px;
height: 22px;
display: inline-block;
line-height: 22px;
background-repeat: no-repeat;
background-position: 0px 0px;
font-size: 120%;
margin: 20px;
vertical-align: middle;
cursor: pointer;
font-family: 'Open Sans', sans-serif;
}
input[type=checkbox].css-checkbox:checked + label.css-label {
background-position: 0 -22px;
}
label.css-label {
background-image:url(http://csscheckbox.com/checkboxes/u/csscheckbox_cc5c7a8c1727e75f2de9c422739d0ad5.png);
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* End Checkboxes */
Since you haven't replied to my question I will assume you're allowing the client to select multiple days, hence using checkboxes.
This will require you to add the class name Days to your checkbox elements.
function CheckBoxes(){
//Get all input type="checkbox elements"
var days = document.querySelectorAll("input[type=checkbox]");
var Selected=0;
//Loop through checkbox elements
for(var i=0; i<days.length; i++){
// Does this element have "Days" in the class name and is it checked?
if(days[i].className.indexOf('Days')>-1 && days[i].checked){
// Yes/True - Add 1 to the Selected Variable
Selected++;
}
}
//Is Selected more than 0?
if(Selected>0){
// One or more checkboxes are checked.
alert("Selection Found!");
}else{
// No checked checkboxes
alert("No Selection Found!");
//Stop the form from being submitted
event.preventDefault();
}
}
<form onSubmit="CheckBoxes();">
<input type="checkbox" class="Days css-checkbox" value="1"/>
<input type="checkbox" class="Days css-checkbox" value="2"/>
<input type="checkbox" class="Days css-checkbox" value="3"/>
<input type="checkbox" class="Days css-checkbox" value="4"/>
<input type="submit" value="Go"/>
</form>
I have put comments in the source code but if you have any questions please leave a comment below and I will get back to you as soon as possible.
If you want to stop the form from submitting you can use event.preventDefault();
I hope this helps. Happy coding!
This worked for me. Thanks again to NewToJS.
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" language="JavaScript">
function CheckBoxes(){
//Get all input type="checkbox elements"
var boxes = document.querySelectorAll("input[type=checkbox]");
var total_Days=0;
var total_Actions=0;
//Loop through checkbox elements
for(var i=0; i<boxes.length; i++){
// Does this element have "Days" in the class name and is it checked?
if(boxes[i].className.indexOf('Days')>-1 && boxes[i].checked){
// Yes/True - Add 1 to the Total_Days Variable
total_Days++;
}
if(boxes[i].className.indexOf('Actions')>-1 && boxes[i].checked){
// Yes/True - Add 1 to the Selected Variable
total_Actions++;
}
}
//Is Selected more than 0?
if(total_Days>0 && total_Actions>0) {
// One or more checkboxes are checked.
}else{
// No checked checkboxes
alert("You must select an action, and at least one day.");
}
}
</script>
</head>
<body>
<div class="box" title="Schedule">
<div class="wrapper">
<a data-popup="On demand" href="#refresh" value="Refresh Now">Refresh Now</a>
</div>
Change Schedule
</div>
<aside class="modal" id="schedule">
<h2 >Refresh Schedule</h2>
<section >
<div class="onoffswitch">
<form name="onoff" method="post" action="{{ url_for('togglecron') }}">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="onoffswitch" onchange="this.form.submit()" {{ checkval }}>
<label class="onoffswitch-label" for="onoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</form>
</div>
<p id="schedule-mssg"><strong>When should this site refresh?</strong></p>
<form method='POST' name="schedule_time" action="{{ url_for('info') }}" onsubmit="CheckBoxes()">
<select class="custom-dropdown" name="hour" id="hour" required>
<option value="" selected disabled>Hour</option>
{% for i in hours %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
<select class="custom-dropdown" name="minute" id="minute" required>
<option value="" selected disabled>Minute</option>
{% for i in minutes %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
<select class="custom-dropdown" name="period" id="period" required>
<option value="" selected disabled>AM/PM</option>
<option>AM</option>
<option>PM</option>
</select>
<input type="checkbox" name="action" id="code" class="Actions css-checkbox" value="code" checked><label for="code" class="css-label">Code</label>
<input type="checkbox" name="action" id="database" class="Actions css-checkbox" value="database" checked><label for="database" class="css-label">Database</label>
<div id="schedule-form">
<input type="checkbox" name="m" id="m" class="Days css-checkbox" value="1" checked><label for="m" class="css-label">Mon</label>
<input type="checkbox" name="t" id="t" class="Days css-checkbox" value="2" checked><label for="t" class="css-label">Tues</label>
<input type="checkbox" name="w" id="w" class="Days css-checkbox" value="3" checked><label for="w" class="css-label">Wed</label>
<input type="checkbox" name="th" id="th" class="Days css-checkbox" value="4" checked><label for="th" class="css-label">Thur</label>
<input type="checkbox" name="f" id="f" class="Days css-checkbox" value="5" checked><label for="f" class="css-label">Fri</label>
<input type="checkbox" name="s" id="s" class="Days css-checkbox" value="6" checked><label for="s" class="css-label">Sat</label>
<input type="checkbox" name="sn" id="sn" class="Days css-checkbox" value="7" checked><label for="sn" class="css-label">Sun</label>
</fieldset>
</div>
<input type="submit" name="sched-sub" id="schedule-sub" value="Save Changes"; />
Close
</form>
</section>
<footer class="cf">
</footer>
</section>
</aside>
<script type="text/javascript">
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select") return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
}
else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {
} else {
i = 1;//unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i==1){
$("#chkSearchAll").attr("checked", false)
}
});
});
</script>
<!-- TinyMCE -->
<script type="text/javascript" src="js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode: "exact",
elements: "txtDesc"
});
</script>
<!-- /TinyMCE -->
<style type="text/css">
.clsChksearch
{
margin:0px;
}
</style>

Categories