I'm writing up a form that has various options with time slots where users can select a window that they works for them. When they select an option that shares the same time frame with another option, the other options are supposed to be disabled until the user deselects the option they clicked. This way they cannot select two options with conflicting times.
The problems I'm running into are:
The options are not re-enabling when a user deselects the checkbox they clicked.
When a user selects a different checkbox, the disabled formatting jumps around to the other options.
What could be causing this to happen?
const activityCheckboxes = document.querySelectorAll('.activities input');
const activityLabels = document.querySelectorAll('.activities label')
document.querySelector('.activities').addEventListener('change', (e) => {
const clicked = e.target;
const clickedTime = clicked.getAttribute('time');
for (let i = 0; i < activityCheckboxes.length; i++) {
const activityTime = activityCheckboxes[i].getAttribute('time');
if (clickedTime === activityTime && clicked !== activityCheckboxes[i]) {
activityCheckboxes[i].setAttribute('disabled', true);
activityLabels[i].style.color = "gray";
activityLabels[i].style.setProperty("text-decoration", "line-through");
} else {
activityCheckboxes[i].removeAttribute('disabled');
activityLabels[i].style.setProperty("color", "initial");
activityLabels[i].style.setProperty("text-decoration", "initial");
}
}
});
<fieldset class="activities">
<legend>Different Time Options</legend>
<label><input type="checkbox" time="3pm"> Option 1 - 3pm </label>
<br />
<label><input type="checkbox" time="1pm"> Option 2 - 1pm </label>
<br />
<label><input type="checkbox" time="4pm"> Option 3 - 4pm </label>
<br />
<label><input type="checkbox" time="1pm"> Option 4 - 1pm </label>
<br />
<label><input type="checkbox" time="3pm"> Option 5 - 3pm </label>
<br />
<label><input type="checkbox" time="3pm"> Option 6 - 3pm </label>
<br />
<label><input type="checkbox" time="4pm"> Option 7 - 4pm </label>
</fieldset>
You do not check if your inputs are checked or not so only one action happens for both cases.
You only check the one input that triggered the event so all the styling/disabling for the other inputs is lost
The snippet below clears all the items then check which ones should be disabled and disables those
const activityCheckboxes = document.querySelectorAll('.activities input');
const activityLabels = document.querySelectorAll('.activities label')
document.querySelector('.activities').addEventListener('change', (e) => {
const clicked = document.querySelectorAll('.activities input:checked');
let selector = 'xxx ';
for (let i = 0; i < clicked.length; i++) {
selector += ',.activities [time="'+clicked[i].getAttribute('time')+'"]:not(:checked)';
}
const clickedTime = document.querySelectorAll(selector);
for (let i = 0; i < activityCheckboxes.length; i++) {
activityCheckboxes[i].removeAttribute('disabled');
activityLabels[i].style.setProperty("color", "initial");
activityLabels[i].style.setProperty("text-decoration", "initial");
}
for (let i = 0; i < clickedTime.length; i++) {
clickedTime[i].setAttribute('disabled', true);
clickedTime[i].style.color = "gray";
clickedTime[i].parentElement.style.setProperty("text-decoration", "line-through");
}
});
<fieldset class="activities">
<legend>Different Time Options</legend>
<label><input type="checkbox" time="3pm"> Option 1 - 3pm </label>
<br />
<label><input type="checkbox" time="1pm"> Option 2 - 1pm </label>
<br />
<label><input type="checkbox" time="4pm"> Option 3 - 4pm </label>
<br />
<label><input type="checkbox" time="1pm"> Option 4 - 1pm </label>
<br />
<label><input type="checkbox" time="3pm"> Option 5 - 3pm </label>
<br />
<label><input type="checkbox" time="3pm"> Option 6 - 3pm </label>
<br />
<label><input type="checkbox" time="4pm"> Option 7 - 4pm </label>
</fieldset>
Related
In my project I want change src part (ar-button's src) related to my radio buttons check.
For ex: When you check "Option 1" I want to change src part on ar-button. Than when you check Option3x(with checked option1 and option1x) I want to change src again.
I mean for all 64 combination of checks I want to change src.
Any help or suggestion would be great!
Thanks..
<label>
<input type="radio" id="diffuse" name="kumas" value="textues/kumas/2/pgwfpjp_2K_Albedo.jpg"checked>
Option1
</label>
<label>
<input type="radio"id="adiffuse" name="kumas" value="textues/kumas/1/oi2veqp_2K_Albedo.jpg">
Option 2
</label>
<label>
<input type="radio" id="bdiffuse"name="kumas" value="textues/kumas/3/sjfvce3c_2K_Albedo.jpg">
Option 3
</label>
<label>
<input type="radio" id="cdiffuse"name="kumas" value="textues/kumas/4/sjfvcjzc_2K_Albedo.jpg">
Option 4
</label>
<br><br>
<label>
<input type="radio" id="diffuse1" name="kol" value="textues\kol\1\teqbcizc_2K_Albedo.jpg" checked>
Option 1x
</label>
<label>
<input type="radio" id="adiffuse1" name="kol" value="textues\kol\2\tfjbderc_2K_Albedo.jpg">
Option 2x
</label>
<label>
<input type="radio" id="bdiffuse1"name="kol" value="textues\kol\3\tcnodi3c_2K_Albedo.jpg">
Option 3x
</label>
<label>
<input type="radio" id="cdiffuse1"name="kol" value="textues\kol\4\tcicdebc_2K_Albedo.jpg">
Option 4x
</label>
</div>
</div>
</div>
<br><br>
<label>
<input type="radio" id="diffuse2" name="dugme" value="textues\metal\1\scksebop_2K_Albedo.jpg" checked>
Option 1z
</label>
<label>
<input type="radio" id="adiffuse2" name="dugme" value="textues\metal\2\se4objgc_2K_Albedo.jpg">
Option 2z
</label>
<label>
<input type="radio" id="bdiffuse2"name="dugme" value="textues\metal\3\se4pcbbc_2K_Albedo.jpg">
Option 3z
</label>
<label>
<input type="radio" id="cdiffuse2"name="dugme" value="textues\metal\4\shkxcgfc_2K_Albedo.jpg">
Option 4z
</label>
<br><br>
<ar-button
id="change" src="https://basebros.com/models/ar_base_tekli_koltuk_3d.glb"
id="change2 ios-src="https://basebros.com/models/ar_base_tekli_koltuk_3d.usdz"
title="3D-AR by BASE">
<img class="arbuttonicon" src="Assets/evindebutton.png" width="170px" alt="AR-icon">
</ar-button>
Try using this code:
const kumas = document.getElementsByName("kumas");
const kol = document.getElementsByName("kol");
const dugme = document.getElementsByName("dugme");
const arButton = document.querySelector("ar-button");
let sources = [[[],[],[],[]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]; /* Fill this with the sources. The first element is if the first option for kumas is selected, the second is for if the second option is selected, etc. The elements inside those elements are for each of the different options for kol, and the elements inside those elements are for each of the different options for dugme. */
function foo() {
let kumasSelected;
let kolSelected;
let dugmeSelected;
for(let i of kumas) {
if(i.checked) {
kumasSelected = kumas.indexOf(i);
}
}
for(let i of kol) {
if(i.checked) {
kolSelected = kol.indexOf(i);
}
}
for(let i of dugme) {
if(i.checked) {
dugmeSelected = dugme.indexOf(i);
}
}
arButton.src = sources[kumasSelected][kolSelected][dugmeSelected];
}
Run the function each time you want to update the source.
<label>
<input type="radio" id="diffuse" name="kumas" value="textues/kumas/2/pgwfpjp_2K_Albedo.jpg"checked>
Option1
</label>
<label>
<input type="radio"id="adiffuse" name="kumas" value="textues/kumas/1/oi2veqp_2K_Albedo.jpg">
Option 2
</label>
<label>
<input type="radio" id="bdiffuse"name="kumas" value="textues/kumas/3/sjfvce3c_2K_Albedo.jpg">
Option 3
</label>
<label>
<input type="radio" id="cdiffuse"name="kumas" value="textues/kumas/4/sjfvcjzc_2K_Albedo.jpg">
Option 4
</label>
<br><br>
<label>
<input type="radio" id="diffuse1" name="kol" value="textues\kol\1\teqbcizc_2K_Albedo.jpg" checked>
Option 1x
</label>
<label>
<input type="radio" id="adiffuse1" name="kol" value="textues\kol\2\tfjbderc_2K_Albedo.jpg">
Option 2x
</label>
<label>
<input type="radio" id="bdiffuse1"name="kol" value="textues\kol\3\tcnodi3c_2K_Albedo.jpg">
Option 3x
</label>
<label>
<input type="radio" id="cdiffuse1"name="kol" value="textues\kol\4\tcicdebc_2K_Albedo.jpg">
Option 4x
</label>
</div>
</div>
</div>
<br><br>
<label>
<input type="radio" id="diffuse2" name="dugme" value="textues\metal\1\scksebop_2K_Albedo.jpg" checked>
Option 1z
</label>
<label>
<input type="radio" id="adiffuse2" name="dugme" value="textues\metal\2\se4objgc_2K_Albedo.jpg">
Option 2z
</label>
<label>
<input type="radio" id="bdiffuse2"name="dugme" value="textues\metal\3\se4pcbbc_2K_Albedo.jpg">
Option 3z
</label>
<label>
<input type="radio" id="cdiffuse2"name="dugme" value="textues\metal\4\shkxcgfc_2K_Albedo.jpg">
Option 4z
</label>
<br><br>
<ar-button
src="https://basebros.com/models/ar_base_tekli_koltuk_3d.glb"
title="3D-AR by BASE">
<img class="arbuttonicon" src="Assets/evindebutton.png" width="170px" alt="AR-icon">
</ar-button>
<script>
const kumas = document.getElementsByName("kumas");
const kol = document.getElementsByName("kol");
const dugme = document.getElementsByName("dugme");
const arButton = document.querySelector("ar-button");
let sources = [[["https://basebros.com/models/ar_base_ayakkabi.glb"],["https://basebros.com/models/ar_base_camasir_makinesi_3d.glb"],["https://basebros.com/models/ar_base_kahve_makinesi_3d.glb"],["https://basebros.com/models/ar_base_nintendo.glb"]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]; /* Fill this with the sources. The first element is if the first option for kumas is selected, the second is for if the second option is selected, etc. The elements inside those elements are for each of the different options for kol, and the elements inside those elements are for each of the different options for dugme. */
function foo() {
let kumasSelected;
let kolSelected;
let dugmeSelected;
for(let i of kumas) {
if(i.checked) {
kumasSelected = kumas.indexOf(i);
}
}
for(let i of kol) {
if(i.checked) {
kolSelected = kol.indexOf(i);
}
}
for(let i of dugme) {
if(i.checked) {
dugmeSelected = dugme.indexOf(i);
}
}
arButton.src = sources[kumasSelected][kolSelected][dugmeSelected];
}
</script>
I have a list of 5 radio buttons, with the last radio button to select a manual entry text (an "other" option). I can't seem to get the form to work for all 5 possibilities - either it returns the radio value or the written value (currently only the written value and not any of the preset radio values). Can't get it to work for all of 5 possible returns.
Here's the javascript to either select text or clear it when unselected:
<script type= "text/javascript" >
function HandleRadioOtherBox(grp, txt)
{
var x, len = grp.length;
for (x =0; x<len; ++x)
{
if (grp[x].checked) break;
}
if (x < len && grp[x].value == txt.name)
{
txt.disabled = false;
txt.select();
txt.focus();
}
else
{
txt.value = "";
txt.disabled = true;
}
return true;
}
window.onload = function ()
{
var ele = document.forms[0].elements;
return HandleRadioOtherBox(ele['OPS'], ele['Country']);
}
</script>
And here, the HTML radio button portion:
<tr valign="top">
<td class="style3">Country: </td>
<td class="copy">
<input type="radio" name="OPS" value="United States" checked="checked"
onclick="return HandleRadioOtherBox(OPS, Country)" /> United States
<input type="radio" name="OPS" value="Canada"
onclick="return HandleRadioOtherBox(OPS, Country)" /> Canada
<input type="radio" name="OPS" value="England"
onclick="return HandleRadioOtherBox(OPS, Country)" /> England
<input type="radio" name="OPS" value="Australia"
onclick="return HandleRadioOtherBox(OPS, Country)" /> Australia <br />
<input type="radio" name="OPS" value="Country"
onclick="return HandleRadioOtherBox(OPS, Country)" /> Other Country:
<input type='text' name="Country" id="Country" maxlength='80' />
</td>
</tr>
Have spent many, many hours with not much of a hole made in the cement (yet). :-)
Help!
You can write a single function for your form which checks for two events:
radio button check
text input blur
and then gives an appropriate response based on which radio button registered a check event or whether the text input registered a blur event:
var radioButtons = document.querySelectorAll('input[type="radio"]');
var otherCountryRadio = document.querySelector('.other-country input[type="radio"]');
var otherCountryText = document.querySelector('.other-country input[type="text"]');
function returnValue() {
if (this === otherCountryRadio) {
otherCountryText.focus();
}
else {
if (this.value.match(/\w/)) {
console.log(this.value);
}
}
}
for (var i = 0; i < radioButtons.length; i++) {
radioButtons[i].addEventListener('change', returnValue, false);
}
otherCountryText.addEventListener('blur', returnValue, false);
div {
margin: 12px;
}
.other-country input[type="text"] {
visibility: hidden;
}
.other-country input:checked + input[type="text"] {
visibility: visible;
}
<form>
<div class="top-countries">
<label><input type="radio" name="OPS" value="United States" checked="checked" /> United States</label>
<label><input type="radio" name="OPS" value="Canada" /> Canada</label>
<label><input type="radio" name="OPS" value="England" /> England</label>
<label><input type="radio" name="OPS" value="Australia" /> Australia</label>
</div>
<div class="other-country">
<label>
<input type="radio" name="OPS" value="Other" /> Other Country
<input type="text" name="Country" />
</label>
</div>
</form>
I wanna know how to use the options from my app as variables in my js. There is 20 total options, which consists of 1 drop down(5 options) and 3 sets of radio buttons(one set of 8, one set of 4, and one set of 3). With each set of possibilities to output the info that fits. I just wanna know how i can collect the chosen options from the user, and output the info that fits the options.. So how to grab clicked dropdown and radio buttons, turn into variables, and output the fitting info once the submit button is clicked.. below is the code i have, pick me apart, tell me what im doing wrong.. Am i even headed in the right direction??
Im a new student, and I'm 100% green to this. Any tips to help get me started would be greatly appreciated. I know that this project is gonna involve lots of coding using only javascript. Thanks
for ex.
Why wont this output?
function league(){
var seasonSelection;
var weekSelection;
var timeSelection;
var typeSelection;
seasonSelection = seasonChoice();
weekSelection = weekDay();
timeSelection = timeChoice();
typeSelction = chooseType();
if(seasonSelection == "all" && weekSelection == "everyday" && timeSelection == "anytime" && typeSelection == "both"){
window.alert("Solberg | Bassett Creek | 6:30PM | 5$ ");
}
}
html code
<form>
<fieldset id="apphead">
<h2>Twin Cities Disc Golf League Finder</h2>
</fieldset>
<fieldset id="season">
<legend><span>Choose a Season</span></legend>
<select id="pickseason">
<option value="all">ALL</option>
<option value="spring">Spring(Mar-May)</option>
<option value="summer">Summer(Jun-Aug)</option>
<option value="fall">Fall(Sep-Nov)</option>
<option value="winter">Winter(Dec-Feb)</option>
</select>
</fieldset>
<fieldset id="weekday">
<legend><span>Choose Day of the Week</span></legend>
<label for="allweek" id="all">
All
<input type="radio" id="wkall" name="dayofweek" class="weekday" value="everyday"/>
</label>
<label for="monday" id="mon">
Mon
<input type="radio" id="wkmon" name="dayofweek" class="weekday" value="monday"/>
</label>
<label for="tuesday" id="tue">
Tue
<input type="radio" id="wktue" name="dayofweek" class="weekday" value="tuesday"/>
</label>
<label for="wednesday" id="wed">
Wed
<input type="radio" id="wkwed" name="dayofweek" class="weekday" value="wednesday"/>
</label>
<label for="thursday" id="thur">
Thur
<input type="radio" id="wkthur" name="dayofweek" class="weekday" value="thursday"/>
</label>
<label for="friday" id="fri">
Fri
<input type="radio" id="wkfri" name="dayofweek" class="weekday" value="friday"/>
</label>
<label for="saturday" id="sat">
Sat
<input type="radio" id="wksat" name="dayofweek" class="weekday" value="saturday" />
</label>
<label for="sunday" id="sun">
Sun
<input type="radio" id="wksun" name="dayofweek" class="weekday" value="sunday" />
</label>
</fieldset>
<fieldset id="time">
<legend><span>Choose a Time of Day</span></legend>
<label for="any" id="anylabel">
Any Time
<input type="radio" id="any" name="timeofday" class="selecttime" value="anytime"/>
</label>
<label for="flex" id="flexlabel">
Flex (All Day)
<input type="radio" id="flex" name="timeofday" class="selecttime" value="flexallday"/>
</label>
<label for="before" id="beforelabel">
Before Noon
<input type="radio" id="before" name="timeofday" class="selecttime" value="beforenoon"/>
</label>
<label for="after" id="afterlabel">
After Noon
<input type="radio" id="after" name="timeofday" class="selecttime" value="afternoon"/>
</label>
</fieldset>
<fieldset id="type">
<legend><span>Choose Type</span></legend>
<label for="both" id="bothlabel">
Both
<input type="radio" id="typeboth" name="ruletypes" class="selecttype" value="both"/>
</label>
<label for="singles" id="singleslabel">
Singles
<input type="radio" id="typesingles" name="ruletypes" class="selecttype" value="singles"/>
</label>
<label for="doubles" id="doubleslabel">
Doubles
<input type="radio" id="typedoubles" name="ruletypes" class="selecttype" value="doubles"/>
</label>
</fieldset>
<fieldset class="buttonbox">
<button onclick="league()" type="button" class="submit">FIND A LEAGUE</button>
</fieldset>
</form>
JavaScript
<script>
function league(){
var seasonSelection;
var weekSelection;
var timeSelection;
var typeSelection;
seasonSelection = seasonChoice();
weekSelection = weekDay();
timeSelection = timeChoice();
typeSelction = chooseType();
if(seasonSelection == "all" && weekSelection == "everyday" && timeSelection == "anytime" && typeSelection == "both"){
window.alert("Solberg | Bassett Creek | 6:30PM | 5$ ");
}
}
function seasonChoice(){
var seasonChoice = document.getElementById("pickseason").value;
return seasonChoice;
}
function weekDay(){
var weekSelection = document.getElementsByClassName("weekday");
var weekValue;
for(var z=0; z <= 8; z++){
if(weekSelection.checked){
weekValue = weekSelection.value;
}
}
return weekValue;
}
function timeChoice(){
var timeSelection = document.getElementsByClassName("selecttime");
var timeValue;
for(var t=0; t <= 4; t++){
if(timeSelection.checked){
timeValue = timeSelection.value;
}
}
return timeValue;
}
function chooseType(){
var typeSelection = document.getElementsByClassName("selecttype");
var typeValue;
for(var y=0; y <= 3; y++){
if(typeSelection.checked){
typeValue = typeSelection.value;
}
}
return typeValue;
}
</script>
First of all, you have a typo in function league(). You're missing an e in typeSelction = chooseType();
Now, when you're iterating through arrays, you need the index, like this -
for (var z = 0; z < 8; z++) {
if (weekSelection[z].checked) {
weekValue = weekSelection[z].value;
}
}
You're basically missing the z which is the index of the array element. Similarly, t and y in other functions.
Here's the link where you can view your full corrected working code. Also, keep in mind when iterating through arrays, do not exceed the array length, i.e., it shouldn't be z <= 8; it should be z < 8. Hope that helps!
You are missing the index while iterating over the radio selections:
if (weekSelection[z].checked) { //missing [z]
weekValue = weekSelection[z].value; //missing [z]
}
Same goes for other functions
if (timeSelection[t].checked) { //missing [t]
timeValue = timeSelection[t].value; //missing [t]
}
Last one:
if (typeSelection[y].checked) { //missing [y]
typeValue = typeSelection[y].value; //missing [y]
}
I have a variable named 'options'. Whenever a user checks one of the checkboxes, I need 'options' to populate the string with the .innerHTML for each checked checkbox. For example, when Instagram and Google+ are checked, 'options' would = Instagram, Google+.
html:
<section id="extra-features">
<div class="span3">
<label class="checkbox" for="Checkbox1">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Instagram
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Review site monitoring
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Google+
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> LinkedIn
</label>
</div>
<div class="span3">
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Pinterest
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> FourSquare
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Tumblr
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Advertising
</label>
</div>
</section>
<div class="card-charge-info">
Your card will be charged $<span id="payment-total">0</span> now, and your subscription will bill $<span id="payment-rebill">0</span> every month thereafter. You can cancel or change plans anytime.
</div>
javascript:
var price = 0,
additional = 0,
options = "",
inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total'),
total2 = document.getElementById('payment-rebill');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.parentNode.className.split(" ").indexOf("checked") > -1 ? 1 : -1);
additional += add
total.innerHTML = price + additional;
if (price == select.options[2].value) {
total2.innerHTML = 0;
}
else {
total2.innerHTML = price + additional;
}
}
}
JSFiddle: http://jsfiddle.net/rynslmns/LQpHQ/
I would recommend tabulating the information each time they change a check state. What you're doing now is problematic; currently you start at 0, but end up being in the negative (total price) quickly by checking and unchecking a couple of options.
Also, options, as a string, will become difficult to keep up with. I'd probbaly make that an array that you can add/remove from (but if you tabulate at the end, there's no worrying).
For example:
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total'),
total2 = document.getElementById('payment-rebill');
// Perform the summing
// Though I'm not sure where total is coming from, but you can work that out.
// And for now I have it alerting the options, but you can do whatever you'd like with that.
function sumItUp(){
var ttl = 0, additional = 0, options = [];
for (var i = 0; i < inputs.length; i++){
if (inputs[i].checked){
options.push(inputs[i].parentNode.textContent.trim());
var n = new Number(inputs[i].value);
if (!isNaN(n)) additional += n;
}
}
total.innerHTML = ttl.toFixed(2);
total2.innerHTML = (ttl + additional).toFixed(2);
alert('Options:\n\n' + options.join(', '));
}
// bind events to sum it on every change
for (var i = 0; i < inputs.length; i++){
inputs[i].addEventListener('change', sumItUp);
}
// Polyfill for trim()
if (!String.prototype.trim){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,'');
};
}
jsFiddle
You won't be able to use .innerHTML to get the text of the checkbox since it doesn't contain any text. You'll want to use .nextSibling instead. Something like this should work:
var price = 0,
additional = 0,
options = "",
inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total'),
total2 = document.getElementById('payment-rebill');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var text = this.nextSibling.nodeValue;
if(options.indexOf(text) != -1) {
options += text + ',';
}
}
}
Of course you'd also want to handle when a checkbox is unselected as well.
I have a form with several checkboxes. I have three categories of checkboxes in the form. I need to limit to a max of three checkboxes per category.
I used this script but it limits to three checkboxes per form.
jQuery(function(){
var max = 3;
var checkboxes = jQuery('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
How do I modify the above script to limit three checkboxes per category within one form?
HTML Example:
<!-- FORM CODE -->
<!-- Start Categories -->
<label>Cat 1</label>
<!-- Checkboxes for Cat 1 - Max of Three in Category -->
<input type="checkbox" value="Option 1" id="CAT_Custom_365571_0" name="CAT_Custom_365571" />Creative<br />
<input type="checkbox" value="Option 2" id="CAT_Custom_365571_1" name="CAT_Custom_365571" />Euphoric<br />
<input type="checkbox" value="Option 3" id="CAT_Custom_365571_2" name="CAT_Custom_365571" />Uplifted<br />
<!-- More checkboxes -->
<label>Cat 2</label>
<!-- Checkboxes for Cat 2 - Max of Three in Category -->
<input type="checkbox" value="Option 1" id="CAT_Custom_365572_0" name="CAT_Custom_365572" />Option 1<br />
<input type="checkbox" value="Option 2" id="CAT_Custom_365572_1" name="CAT_Custom_365572" />Option 2<br />
<input type="checkbox" value="Option 3" id="CAT_Custom_365572_2" name="CAT_Custom_365572" />Option 3<br />
<!-- More checkboxes -->
<label>Cat 3</label>
<!-- Checkboxes for Cat 3 - Max of Three in Category -->
<input type="checkbox" value="Option 1" id="CAT_Custom_365573_0" name="CAT_Custom_365573" />Option 1<br />
<input type="checkbox" value="Option 2" id="CAT_Custom_365573_1" name="CAT_Custom_365573" />Option 2<br />
<input type="checkbox" value="Option 3" id="CAT_Custom_365573_2" name="CAT_Custom_365573" />Option 3<br />
<!-- More checkboxes -->
<!-- MORE FORM CODE -->
Note: The CAT_Custom_365571_2 etc is generated by the CMS I use.
Try (if your markup matches the one in the fiddle)
jQuery(function(){
var max = 3;
var checkboxes = jQuery('input[type="checkbox"]');
checkboxes.click(function(){
var $this = $(this);
var set = $this.add($this.prevUntil('label')).add($this.nextUntil(':not(:checkbox)'));
var current = set.filter(':checked').length;
return current <= max;
});
});
Demo: Fiddle
Update:
Since you have a name for the checkboxes
jQuery(function(){
var max = 3;
var checkboxes = jQuery('input[type="checkbox"]');
checkboxes.click(function(){
var $this = $(this);
var set = checkboxes.filter('[name="'+ this.name +'"]')
var current = set.filter(':checked').length;
return current <= max;
});
});
Demo: Fiddle
jQUERY
$("input[name=chk]").change(function(){
var max= 3;
if( $("input[name=chk]:checked").length == max ){
$("input[name=chk]").attr('disabled', 'disabled');
$("input[name=chk]:checked").removeAttr('disabled');
}else{
$("input[name=chk]").removeAttr('disabled');
}
});
HTML
<input type="checkbox" name"chk" value="A"/>A
<input type="checkbox" name"chk" value="B"/>B
<input type="checkbox" name"chk" value="C"/>C
<input type="checkbox" name"chk" value="D"/>D
<input type="checkbox" name"chk" value="E"/>E
<input type="checkbox" name"chk" value="F"/>F
<input type="checkbox" name"chk" value="F"/>G
FIDDLE EXAMPLE IS HERE
Try this:
jQuery(function(){
var max = 3;
var categories = jQuery('label'); // use better selector for categories
categories.each(function(){
var checkboxes = $(this).find('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
});
just add a class to all the related check boxes, and just use the class selector when checking the checkboxes for a category.
eg:
HTML
<label>Cat 1</label>
<input type='checkbox' class='cat1' />
<input type='checkbox' class='cat1' />
<input type='checkbox' class='cat1' />
<label>Cat 2</label>
<input type='checkbox' class='cat2' />
<input type='checkbox' class='cat2' />
<input type='checkbox' class='cat2' />
...
JS
jQuery(function(){
var max = 3;
var cat1_checkboxes = jQuery('input.cat1[type="checkbox"]');
var cat2_checkboxes = jQuery('input.cat2[type="checkbox"]');
var cat3_checkboxes = jQuery('input.cat3[type="checkbox"]');
cat1_checkboxes.change(function(){
var current = cat1_checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
cat2_checkboxes.change(function(){
var current = cat2_checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
cat3_checkboxes.change(function(){
var current = cat3_checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
This is a newbie code with javascript. It's like working...hardly...
I call this function on each input.
But there is surely a way to call this function one time.
It's working but uncheking a random checkbox from thoses who call it.
<input type="checkBox" name="cat1" value="education" onClick="just2cat();">Education
<input type="checkBox" name="cat2" value="faith" onClick="just2cat();">Religions
<input type="checkBox" name="cat3" value="news" onClick="just2cat();">News
function just2cat()
{
var allInp = document.getElementsByTagName('input');
const MAX_CHECK_ = 2; /*How many checkbox could be checked*/
var nbChk =0;
for(var i= 0; i<allInp.length; i++)
{
if(allInp[i].type.toLowerCase()=='checkbox' && allInp[i].checked) /*OR
if(allInp[i].type.toLowerCase()=='checkbox' && allInp[i].checked===true) */
{
nbChk++;
if(nbChk > MAX_CHECK_)
{
alert("At most 2 categories can be chosen");
allInp[i].checked=false; /* try to Unchek the current checkbox :'( */
}
}
}
}