Checking to see if a checkbox is selected before searching - javascript

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>

Related

JQuery - Allow Specific 2 Checkboxes to be Selected

I only want 1 checkbox to be selected - UNLESS its checkbox 3 AND 4 - then I want to allow these 2 checkboxes to be selected. This is the only time I want 2 checkboxes allowed.
I have a working example of only allowing 1 checkbox. see the jsfiddle...
https://jsfiddle.net/rbla/s1setkfe/3/
I need to allow #3 and #4 to be selected
$(function() {
$('#submit').click(function() {
checked = $("input[type=checkbox]:checked").length;
if (!checked) {
alert("You must check at least one reason.");
return false;
}
});
});
// No more than 1 checkbox allowed
var limit = 1;
$('input.sing-chbx').on('change', function(evt) {
if ($("input[name='choice[]']:checked").length > limit) {
this.checked = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="formname" method="post" autocomplete="off" id="update">
<div class="group" style="margin:0.5em 0;">
<div>
<div id="one">
<input type="checkbox" class="sing-chbx" id="choice" name="choice[]" value="01">
<label>One</label><br/>
</div>
<div id="two">
<input type="checkbox" class="sing-chbx" name="choice[]" value="02">
<label>Two</label><br/>
</div>
<div id="three">
<input type="checkbox" class="sing-chbx" name="choice[]" value="03">
<label>Three</label><br/>
</div>
<div id="four">
<input type="checkbox" class="sing-chbx" name="choice[]" value="04">
<label>Four</label><br/>
</div>
<div id="five">
<input type="checkbox" class="sing-chbx" name="choice[]" value="05">
<label>Five</label><br/>
</div>
</div>
</div>
<input type="submit" id="submit" value="Confirm Submission">
</form>
I have created a fiddle for you demonstrating my solution.
I changed the way you're handling this to be more visual to the user with what is happening by actually disabling the other checkboxes.
I added new classes to all of the checkboxes that only allow one selection, and added a separate class to the checkboxes that allow two selections.
After that you just need to check the class of the clicked checkbox, and disable the others depending on whether or not it was a select-one or select-two checkbox:
var canOnlySelectOne = $(this).hasClass("select-one");
if (canOnlySelectOne) {
$(".sing-chbx").not(this).attr("disabled", this.checked);
} else if ($(this).hasClass("select-two")) {
if ($(".select-two:checked").length > 0) {
$(".select-one").attr("disabled", true);
} else {
$(".select-one").attr("disabled", this.checked);
}
}
We simply enable/disable the other checkboxes based on whether or not the clicked one (this) is checked or not. If the checkbox has a class of select-two then we check if any of the select-two checkboxes are checked, and act accordingly.
Instead of preventing user to check - just uncheck prev selection
You have 3 cases: 03 is clicked, 04 is clicked, something else clicked
Here is the updated code:
$(function() {
$('#submit').click(function() {
checked = $("input[type=checkbox]:checked").length;
if (!checked) {
alert("You must check at least one reason.");
return false;
}
});
});
// No more than 1 checkbox allowed except 3 & 4
$('input.sing-chbx').on('change', function(evt) {
var me = $(this).val();
$('input.sing-chbx').each(function(ix){
var el = $(this);
if(el.val()!= me) {
if(me == "03") {
// case 1: me == '03' - disable all but '04'
if( el.val() != "04") {
el.prop('checked', false);
}
} else if(me == "04") {
// case 2: me == '04' - disable all but '03'
if(el.val() != "03") {
el.prop('checked', false);
}
} else {
// otherwise disable all
el.prop('checked', false);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="formname" method="post" autocomplete="off" id="update">
<div class="group" style="margin:0.5em 0;">
<div>
<div id="one">
<input type="checkbox" class="sing-chbx" id="choice" name="choice[]" value="01">
<label>One</label><br/>
</div>
<div id="two">
<input type="checkbox" class="sing-chbx" name="choice[]" value="02">
<label>Two</label><br/>
</div>
<div id="three">
<input type="checkbox" class="sing-chbx" name="choice[]" value="03">
<label>Three</label><br/>
</div>
<div id="four">
<input type="checkbox" class="sing-chbx" name="choice[]" value="04">
<label>Four</label><br/>
</div>
<div id="five">
<input type="checkbox" class="sing-chbx" name="choice[]" value="05">
<label>Five</label><br/>
</div>
</div>
</div>
<input type="submit" id="submit" value="Confirm Submission">
</form>

Hide and reveal checkbox options - Tidy up Jquery

So I am a relative novice to JS and the Jquery library. I have been playing around with something and can see it is extremely untidy, this is where I was hoping you guys could help suggest a better way of doing what I am trying to acheive.
Aim:
To have multiple checkboxes, some of which if selected reveal a sub set of checkboxes. If the parent is unchecked the children checkboxes should also become unchecked.
HTML (this is simplified)
<div class="option1">
<input type="checkbox" id="optionA" />
<div id="suboption1">
<input type="checkbox" id="optionA1" />
<input type="checkbox" id="optionA2" />
</div>
</div>
<div class="option2">
<input type="checkbox" id="optionB" />
<div id="suboption2">
<input type="checkbox" id="optionB1" />
<input type="checkbox" id="optionB2" />
</div>
</div>
<div class="option3">
<input type="checkbox" id="optionC" />
<div id="suboption3">
<input type="checkbox" id="optionC1" />
<input type="checkbox" id="optionC2" />
</div>
</div>
<!--No sub options on some-->
<div class="option4">
<input type="checkbox" id="optionD" />
</div>
JS
/*Option 1*/
$("#suboption1").hide();
$("#optionA").click(function() {
revealOptionA();
});
function revealOptionA(){
if($('#optionA').is(":checked")) {
$("#suboption1").show('hide');
} else {
$("#suboption1").hide('hide');
$("#optionA1").attr('checked', false);
$("#optionA2").attr('checked', false);
}
}
revealOptionA();
/*Option 2*/
$("#suboption2").hide();
$("#optionB").click(function() {
revealOptionB();
});
function revealOptionB(){
if($('#optionB').is(":checked")) {
$("#suboption2").show('hide');
} else {
$("#suboption2").hide('hide');
$("#optionB1").attr('checked', false);
$("#optionB2").attr('checked', false);
}
}
revealOptionB();
/*Option 3*/
$("#suboption3").hide();
$("#optionC").click(function() {
revealOptionC();
});
function revealOptionC(){
if($('#optionC').is(":checked")) {
$("#suboption3").show('hide');
} else {
$("#suboption3").hide('hide');
$("#optionC1").attr('checked', false);
$("#optionC2").attr('checked', false);
}
}
revealOptionC();
I have put together a quick JSFiddle to better demonstrate!
https://jsfiddle.net/j5pdq8p8/2/
Any advice is greatly appreciated!
I have added class for parent checkbox and the container div which have all child checkboxes. Using this way we can reduce js code.
Please check the below code.
HTML
<div class="option1">
<input type="checkbox" id="optionA" class="parent"/>
<div id="suboption1" class="child">
<input type="checkbox" id="optionA1" />
<input type="checkbox" id="optionA2" />
</div>
</div>
<div class="option2">
<input type="checkbox" id="optionB" class="parent"/>
<div id="suboption2" class="child">
<input type="checkbox" id="optionB1" />
<input type="checkbox" id="optionB2" />
</div>
</div>
<div class="option3">
<input type="checkbox" id="optionC" class="parent"/>
<div id="suboption3" class="child">
<input type="checkbox" id="optionC1" />
<input type="checkbox" id="optionC2" />
</div>
</div>
<!--No sub options on some-->
<div class="option4">
<input type="checkbox" id="optionD" />
</div>
JS
$(document).ready(function() {
$(".child").hide();
$(".parent").change(function(){
if ($(this).prop("checked") == false) {
$(this).parent().find(".child").find(":checkbox").each(function() {
$(this).prop('checked', false);
});
$(this).parent().find(".child").hide();
}
else {
$(this).parent().find(".child").show();
}
});
});
For reference I have created this Fiddle
Here an example with classes instead of id
(updated with uncheck on parent-option click)
JS then HTML
$(".suboptions").toggle();
$('.options').on("click", function() {
$(this).siblings(".suboptions").toggle();
$(this).siblings(".suboptions").children().prop( "checked", false );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" class="options" />
<div class="suboptions">
<input type="checkbox" />
<input type="checkbox" />
</div>
</div>
<div>
<input type="checkbox" class="options" />
<div class="suboptions">
<input type="checkbox" />
<input type="checkbox" />
</div>
</div>
<div>
<input type="checkbox" class="options" />
<div class="suboptions">
<input type="checkbox" />
<input type="checkbox" />
</div>
</div>
<!--No sub options on some-->
<div>
<input type="checkbox" class="options" />
</div>
Based on my understanding to your question, you have 2 requirements,
To have multiple checkboxes, some of which if selected reveal a sub set of checkboxes.
If the parent is unchecked the children checkboxes should also become unchecked.
I believe you have done first already and asking for help to implement two,
I created a fiddle for second implementation,
fiddle: https://jsfiddle.net/j5pdq8p8/8/
Use prop instead of attr for toggling checked or disabled property in jquery
This should be your code. And I UPDATED your jsFiddle
/*Option 1*/
$("#suboption1").hide();
$("#optionA").click(function() {
revealOptionA();
});
function revealOptionA(){
if($('#optionA').is(":checked")) {
$("#suboption1").show('hide');
$("#optionA1").attr('checked', true);
$("#optionA2").attr('checked', true);
} else {
$("#suboption1").hide('hide');
$("#optionA1").attr('checked', false);
$("#optionA2").attr('checked', false);
}
}
revealOptionA();
/*Option 2*/
$("#suboption2").hide();
$("#optionB").click(function() {
revealOptionB();
});
function revealOptionB(){
if($('#optionB').is(":checked")) {
$("#suboption2").show('hide');
$("#optionB1").attr('checked', true);
$("#optionB2").attr('checked', true);
} else {
$("#suboption2").hide('hide');
$("#optionB1").attr('checked', false);
$("#optionB2").attr('checked', false);
}
}
revealOptionB();
/*Option 3*/
$("#suboption3").hide();
$("#optionC").click(function() {
revealOptionC();
});
function revealOptionC(){
if($('#optionC').is(":checked")) {
$("#suboption3").show('hide');
$("#optionC1").attr('checked', true);
$("#optionC2").attr('checked', true);
} else {
$("#suboption3").hide('hide');
$("#optionC1").attr('checked', false);
$("#optionC2").attr('checked', false);
}
}
revealOptionC();

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();

Display Checkboxes on Click of a button

I have a button Resend , and on click of it , the checkboxes get enable against the following:
id="AlertSent"
id="AlertNotSent"
id="AlertInProgress"
Now the DIV Code for Above mentioned DIVS is as below
<div class="span9">
<div class="row-fluid">
<div id="enableCheckBox" class ="span12">
<input type="checkbox" id="checkbox1" name="checkbox1"/>
</div>
<div id="AlertSent" class="span12">
<label><spring:message code='alert.sent' />:</label>
</div>
</div>
<div class="row-fluid">
<div id="enableCheckBox" class ="span12">
<input type="checkbox" id="checkbox2" name="checkbox2"/>
</div>
<div id="AlertNotSent" class="span12">
<label><spring:message code='alert.not.sent'/>:</label>
</div>
</div>
<div class="row-fluid">
<div id="enableCheckBox" class ="span12">
<input type="checkbox" id="checkbox3" name="checkbox3" class="required" />
</div>
<div id="AlertInProgress" class="span12">
<label> <spring:message code='alert.in.progress' />:</label>
</div>
</div>
</div>
The button Code for Resend and Done is
<input type="button" value="button" id="resend"/>
<input type="button" value="button" id="done"/>
The JQuery Code is
var j$ = jQuery.noConflict();
j$(document).ready(function() {
var resendbtn = j$('#resend');
var allChkBox = j$('input[name="enableCheckBox"]');
var verifyChecked = function() {
if ! $('#resend').click {
allChkBox.attr('disabled', 'disabled');
} else {
allChkBox.removeAttr('disabled');
}
};
verifyChecked();
resendbtn.change(verifyChecked);
});
The requirement is on click of Resend, the checkboxes appear against above DIVS (AlertSent, AlertNotSent and AlertInProgress), and the Resend button Becomes Done, and if a User unchecks all the checkboxes then the Done Button becomes Resend again.
How do I write a JQuery/JavaScript code to achieve above?
Please suggest
It's hard to know exactly what you want here, but perhaps this will get you started:
http://jsfiddle.net/ZqH7B/
to handle showing the checkboxes:
$("#resend").on( 'click', function () {
$('.enableCheckBox').css('visibility', 'inherit');
$(this).hide().next().show();
$('input:checkbox').prop('checked', true);
});
to handle uncheck behavior:
$('input[type=checkbox]').on( 'change', function() {
var num = $('input:checked').length;
if ( num == 0 ) { $('#resend').show().next().hide(); }
});
Try following code:
HTML:
<input type="checkbox" class="chk">
<input type="button" value="Resend" class="toggle">
JS:
$(document).ready(function(){
$(".chk").prop("checked","checked");
$(".chk").css('display','none');
$(".toggle").click(function(){
$(".chk").css('display','block');
$(".chk").prop("checked","checked");
$(this).val("Done");
});
$(".chk").change(function(){
var all = $(".chk").length;
var chked = $(".chk").not(":checked").length;
if(all == chked){
$(".chk").css('display','none');
$(".toggle").val("Resend");
}
})
});
JSFIDDLE DEMO

jquery .prop('disabled', true) not working

I am attempting to toggle disabled = true|false on a <input type="text">, using a checkbox. I am able to get the value of the input, but I cannot set the input to disabled.
my jquery/js code
<script>
$(function () {
$('.date').datepicker();
$('body').on('change', '.housing', function () {
if ($(this).val() == 'dorms') {
$(this).parent().next(".dorms").show();
} else {
$(this).parent().siblings(".dorms").hide();
}
});
$('body').on('change', '.single', function () {
if ($(this).checked) {
$('#echo1').text($(this).prev(".roommate").val()); // this works
$(this).prev(".roommate").val(''); // does not empty the input
$(this).prev(".roommate").disabled = true; // does not set to disabled
$(this).prev(".roommate").prop('disabled', true); // does not set to disabled
$('#echo2').text($(this).prev(".roommate").prop('disabled')); // always says false
} else {
$('#echo1').text($(this).prev(".roommate").val()); // this works
$(this).prev(".roommate").disabled = false; // always stays false
$('#echo2').text($(this).prev(".roommate").prop('disabled')); // always says false
}
});
});
</script>
my html code
<div class="registration_housing particpant_0" data-sync="0">
<div>
<label class="particpant_0"></label>
</div>
<div>
<label>Off Campus (not included)</label>
<input type="radio" name="housing[0]" value="none" class="housing" />
</div>
<div>
<label>On Campus</label>
<input type="radio" name="housing[0]" value="dorms" class="housing" />
</div>
<div class="dorms" style="display:none;">
<div>
<label>Checkin:</label>
<input type="text" name="check_in[0]" class="date" />
</div>
<div>
<label>Checkout:</label>
<input type="text" name="check_out[0]" class="date" />
</div>
<div>
<label>Roommate:</label>
<input type="text" name="roommate[0]" class="roommate" />
<input type="checkbox" name="roommate_single[0]" value="single" class="single" />check for singe-occupancy</div>
</div>
<div class="line">
<hr size="1" />
</div>
</div>
<div>
<label id="echo1"></label>
</div>
<div>
<label id="echo2"></label>
</div>
you can see this at http://jsfiddle.net/78dQE/1/
Any idea why I can get the value of (".roommate") - ie. $(this).prev(".roommate").val()
but
$(this).prev(".roommate").disabled = true;
OR
$(this).prev(".roommate").prop('disabled', true);
will not set (".roommate") to disabled?
Your issue is mixing jquery with DOM element attributes
change if ($(this).checked) { to if (this.checked) {
With jquery you would do
$(this).is(':checked') // But you could just do this.checked
And
$(this).prev(".roommate").prop('disabled', false); // or $(this).prev(".roommate")[0].disabled = false;
instead of
$(this).prev(".roommate").disabled = false;
Fiddle
So you just probably need this:
$('body').on('change', '.single', function () {
$(this).prev(".roommate").prop('disabled', this.checked).val('');
});

Categories