Showing/hiding divs based on checkbox using jQuery - javascript

I have a form with a checkbox (contained within a label #contact). For the change action of this checkbox, I am showing/hiding a div (#options).
To ensure that if the checkbox is checked the #options div always is always shown (and avoid the situation where checking the checkbox actually hides the subjequent options), I am using this code:
$('#contact :checkbox').is(':checked') ? $("#options").show() : $("#options").hide();
This works fine. The problem I have is that instead of a single checkbox with an ID, I want to have multiple checkboxes. I want to show/hide the next instance of my .hidden class based on whether the previous checkbox (within a label with the class .trigger) is checked or not. I have tried this:
$(document).ready(function() {
if( $('.trigger :checkbox').is(':checked') ) {
$(this).parent().nextAll('ul.hidden').show();
} else {
$(this).parent().nextAll('ul.hidden').hide();
}
});
But to no avail. The checkboxes are in an unordered list, like this:
<ul>
<li><label class="trigger"><input type="checkbox" name="02" /> Trigger 1</label>
<ul class="hidden">
<li><label><input type="checkbox" name="02-sub1" /> Normal</label></li>
<li><label><input type="checkbox" name="02-sub2" /> Normal</label></li>
</ul>
</li>
<li><label><input type="checkbox" name="02" /> Normal</label></li>
<li><label><input type="checkbox" name="03" /> Normal</label></li>
<li><label class="trigger"><input type="checkbox" name="04" /> Trigger 2</label>
<ul class="hidden">
<li><label><input type="checkbox" name="04-sub1" /> Normal</label></li>
<li><label><input type="checkbox" name="04-sub2" /> Normal</label></li>
</ul>
</li>
</ul>
I can't see where I'm going wrong here; presumably my selector is incorrect, but I've played around with the syntax for ages and not got anywhere. Thanks in advance (and thank you for reading this far).

You need to run your code inside a change handler, so this refers to the checkbox you want, like this:
$(document).ready(function() {
$('.trigger :checkbox').change(function() {
if( $(this).is(':checked') ) {
$(this).parent().nextAll('ul.hidden').show();
} else {
$(this).parent().nextAll('ul.hidden').hide();
}
});
});
...and that can be made much shorter with .toggle(bool), like this:
$(function() {
$('.trigger :checkbox').change(function() {
$(this).parent().nextAll('ul.hidden').toggle(this.checked);
});
});
If you need it to run when the page loads, so the show/hide states match the checkbox, just call that change handler with .change() (shortcut for .trigger('change')), like this:
$(function() {
$('.trigger :checkbox').change(function() {
$(this).parent().nextAll('ul.hidden').toggle(this.checked);
}).change();
});

You know you can roll your own fields, right? The typical way to do that is with a "rel=" field that has no meaning in HTML but can be picked up and used in jquery.
if ($('#contact :checkbox').is(':checked')) {
$("#" + $('#contact :checkbox').attr('rel')).show();
} else {
$("#" + $('#contact :checkbox').attr('rel')).hide();
}
And then:
<li><label class="trigger"><input type="checkbox" name="04" rel="hidden-04" /> Trigger 2</label>
<ul class="hidden" id="hidden-04">
<li><label><input type="checkbox" name="04-sub1" /> Normal</label></li>
<li><label><input type="checkbox" name="04-sub2" /> Normal</label></li>
</ul>
</li>
So then, when the checkbox named 04 is checked, we look in its rel field for the id of the object to hide() or show(). I think that's a LOT easier than trying to walk the dom to find the target object.

Related

How to limit the checked checkboxes to just one at a time?

I am trying to create a filter using checkboxes. I need to only have one checkbox checked at a time. How do I do this?
Scenario: The page has a catalog of watches. The user wants to filter the watches according to for men or for women
Here is my code:
$("#filter-options :checkbox").click(function()
{
$(".collection-wrapper .strap-wrapper").hide();
$("#filter-options :checkbox:checked").each(function()
{
$("." + $(this).val()).fadeIn();
});
if($('#filter-options :checkbox').filter(':checked').length < 1)
{
$(".collection-wrapper .strap-wrapper").fadeIn();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Filter Items</h3>
<ul id="filter-options">
<li><input type="checkbox" value="filter_man" data-filter_id="man"> Man</li>
<li><input type="checkbox" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>
<div class="collection-wrapper">
<div class="strap-wrapper filter_man">
<h2>man</h2>
<p></p>
</div>
<div class="strap-wrapper filter_woman">
<h2>woman</h2>
<p></p>
</div>
<div class="strap-wrapper filter_man filter_woman">
<h2>man / woman</h2>
<p></p>
</div>
<div class="strap-wrapper filter_woman">
<h2>woman</h2>
<p></p>
</div>
</div>
Thanks in advance!
Checkboxes are used for selecting multiple values of choices. What you need is Radio Buttons. They are used exactly for this purpose. One can select only one radio button at a time. So replace your code with:
<ul id="filter-options">
<li><input type="radio" name="filter" value="filter_man" data-filter_id="man"> Man</li>
<li><input type="radio" name="filter" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>
See an example here: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio
Radio buttons are what you are looking for ;)
take at look at these links:
jQuery api demo
Fiddle example
HTML:
<form id="myForm">
<input type="radio" name="myRadio" value="1" /> 1 <br />
<input type="radio" name="myRadio" value="2" /> 2 <br />
<input type="radio" name="myRadio" value="3" /> 3 <br />
</form>
JS
$('#myForm input').on('change', function() {
alert($('input[name="myRadio"]:checked', '#myForm').val());
});
You could use radio buttons or you could do something like:
$('input[type=checkbox]').change(function(){
if ($('input[type=checkbox]:checked').length > 1) {
this.checked = false;
}
})
You could just use radio buttons, but if you want to do it with checkboxes, solution is pretty simple.
When you click on one of the checkboxes, select all the checkboxes and remove "checked" state, and then just add checked on clicked checkbox
Something like this:
// On checkbox click
$("#filter-options input[type=checkbox]").click(function(event) {
// Uncheck all checkboxes
$("#filter-options input[type=checkbox]").prop("checked", false);
// Check that one that you clicked
$(this).prop("checked", true)
});

Checkbox - Getting multiple check boxes checked on checking only one

I am trying to implement a check box which checks all the check boxes on the page. But when I changed the code slightly, it stopped working. I want to keep the changed code and still want the functionality to be working. Kindly help!
* Kindly ignore the missing tags if any. It is correct unless I made mistake in editing the question.
<script>
function toggle(source) {
checkboxes = document.getElementsByName('qchecked[]');
for(var i=0, n=checkboxes.length;i<n;i++){
checkboxes[i].checked = source.checked;
}
}
</script>
<html>
/* Code for the check box which when checked, checks all the checkbox. */
<input type='checkbox' class='css-checkbox' id='checkbox' onClick='toggle(this)'/>
<label for='checkbox' class='css-label lite-y-green'></label>
/* Code for the check boxes which should be checked when the check box with id=checkbox is checked.
I changed the code from INITIAL CODE to CHANGED CODE for some other purpose and the toggle stopped working.
Now clicking on that one check box is not marking or un marking all the check boxes. */
<!-- INITIAL CODE -->
<input type='checkbox' id='yes_checkbox[$index]' class='css-checkbox' name='qchecked[]'/>
<label for='yes_checkbox[$index]' class='css-label lite-y-green'></label>
<!-- CHANGED CODE -->
<input type='checkbox' id='yes_checkbox[$index]' class='css-checkbox' name='qchecked[$array6[qID]]'/>
<label for='yes_checkbox[$index]' class='css-label lite-y-green'></label>
</html>
Instead of name, give a class to all elements and you should use by
getElementsByClassName('your_class');
Since you name of inputs are different, you can make use of common class
checkboxes = document.getElementsByClassName('css-checkbox');
Try this..
<ul class="chk-container">
<li><input type="checkbox" id="selecctall"/> Selecct All</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item1"> This is Item 1</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item2"> This is Item 2</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item3"> This is Item 3</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item4"> This is Item 4</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item5"> This is Item 5</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item6"> This is Item 6</li>
<li><input class="checkbox2" type="checkbox" name="check[]" value="item6"> Do not select this</li>
</ul>
$(document).ready(function() {
$('#selecctall').click(function(event) { //on click
if(this.checked) { // check select status
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
});
demo:https://jsfiddle.net/go1gL743/

Check if its the first checkbox is clicked

I have a list of checkboxes like so:
<div class="checkbox-list">
<label><input type="checkbox" value="" /> All items</label><br />
<label><input type="checkbox" value="1" /> First item</label><br />
<label><input type="checkbox" value="2" /> Second item</label><br />
<label><input type="checkbox" value="3" /> Third item</label><br />
<label><input type="checkbox" value="4" /> Forth Checkbox</label>
</div>
The behavior I am looking for is if I select the first checkbox in this div (.checkbox-list input[type=checkbox]:first) all other checkboxes after is checked off. Likewise if I select any other than the first, the first one is deselected.
I am struggling on how to check if the first one is clicked on?
$(".checkbox-list").on("change", "input[type=checkbox]", function () {
if ($(this).first()) { // <- not working - how do I know if I clicked the first one?
$("input[type=checkbox]:checked", ".checkbox-list").not(this).prop("checked", false);
$(this).prop("checked", true);
} else {
// Uncheck first checkbox
}
});
Here is a fiddle if you wish to play around: http://jsfiddle.net/4c7aubqL/1/
jsBin demo
$(".checkbox-list").on("change", ":checkbox", function() {
var $all = $(".checkbox-list").find(":checkbox");
var $first = $all.eq(0);
if ($first.is(":checked")) {
$all.not(this).prop("checked", false);
}
});
You should be using radio buttons, not checkboxes. That will do exactly what you want, with no additional effort on your part. Even if you succeed in what you are trying to do, the user interface will look wrong.

finding value of closest hidden field, located above user click in javascript

I'm trying to grab the value of a hidden field that resides above each group of LI's with javascript, I cannot use jQuery because of an unreasonable client's concerns (believe me, I've tried, they just don't want to "risk" adding a library)... anyway...
The list would look something like this:
<input id="hidden1" type="hidden" value="5" class="includeds">
<h3>header</h3>
<ul class="groups">
<li><input id="li1" type="checkbox" value="1" onclick="value()"></li>
<li><input id="li2" type="checkbox" value="2" onclick="value()"></li>
<li><input id="li3" type="checkbox" value="3" onclick="value()"></li>
</ul>
<input id="hidden2" type="hidden" value="3" class="includeds">
<h3>header2</h3>
<ul class="groups">
<li><input id="li4" type="checkbox" value="4" onclick="value()"></li>
<li><input id="li5" type="checkbox" value="5" onclick="value()"></li>
<li><input id="li6" type="checkbox" value="6" onclick="value()"></li>
</ul>
So if I click on checkbox li1, I want to retrieve the value "5" from the hidden field above it.
If I click li5, I want to get the value of "2" from the first hidden field above it, etc, etc.
in a previous SO question some amazing people helped me do this with jQuery:
if($(this).closest('ul').prevAll('.includeds:first').val() !== '0') {
// logic here
}
but when presented to the client, I ran into the aforementioned complaints. So now I need to do the same thing with javascript vanilla. I appreciate any help or pointers you guys could provide. I apologize for asking the same question twice, between jquery and javascript.
Uhm, the jQuery code I'd use would be:
$(this).parent().prev().prev().val()
With that in mind, all you have to do is rewrite the code to correct plain javascript entities.
The result would be something like:
function getParent(node){
return node.parentNode;
}
function getPrev(node){
do { // loop to find the previous node that is an element
node = node.previousSibling;
}while(node && node.nodeType != 1);
return node;
}
getPrev(getPrev(getParent(this))));
If you can't use jQuery then complex queries like the on you mentioned become much more difficult. In liue of jQuery it's easiest to reference elements by their ID tag or by a class filter (depending on the scenario).
Here i would say the best bet is to hard code the given input ID into the onclick function.
HTML
<input id="hidden2" type="hidden" value="3" class="includeds">
<h3>header2</h3>
<ul class="groups">
<li><input id="li4" type="checkbox" value="4" onclick="value('hidden2')"></li>
<li><input id="li5" type="checkbox" value="5" onclick="value('hidden2')"></li>
<li><input id="li6" type="checkbox" value="6" onclick="value('hidden2')"></li>
</ul>
JavaScript
function value(id) {
var elem = document.getElementByID(id);
...
}

jQuery Validation Plugin Multiple Checkboxes

I am having some difficulty in using the jQuery Validator plugin. I have a list of checkboxes with different name attributes and I can't seem to figure out how to ensure that at least one of them has been checked. Everything that I find on Google seems to only work when the name attribute is the same.
Here is some sample code (updated):
<ul id="email_lists">
<li>
<input name="checkbox1" type="checkbox" /> List 1
</li>
<li>
<input name="checkbox2" type="checkbox" /> List 2
</li>
<li>
<input name="checkbox3" type="checkbox" /> List 3
</li>
<li>
<input name="checkbox4" type="checkbox" /> List 4
</li>
</ul>
I want to make sure that at least one of those is checked. Unfortunately, I cannot make the names the same as it is form that submits to a third-party email marketing application and it is expecting specific name attributes for these checkboxes.
Update
I am aware of how to do this using plain jQuery, but I would prefer to use the jQuery Validator plugin since that is how all of the other validation on the page is done.
I can group those checkboxes using jQuery by saying $('#email_lists li');, but I'm not really sure how to use something like that and tell the jQuery Validator plugin to use that as a group.
Assuming that you can give the checkboxes a class name (the jQuery needs something to work with):
<input class="validationGroupOne" name="checkbox1" type="checkbox" />
<input class="validationGroupOne" name="checkbox2" type="checkbox" />
<input class="validationGroupOne" name="checkbox3" type="checkbox" />
<input class="validationGroupOne" name="checkbox4" type="checkbox" />
You should be able to plug in the .validationGroupOne class-selector in place of the, usual, name attribute.
This was my solution :-)
Use:
<div id="list">
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
</div>
<input type="hidden" name="the_real_field_name" />
Then in jquery validate plugin block:
rules : {
chkbox: "required"
},
Then store the values as an array into a single hidden field like:
function updateInput() {
var allVals = [];
$('#list :checked').each(function() {
allVals.push($(this).val());
});
$('#the_real_field_name').val(allVals);
}
$(function() {
$('#list input').click(updateInput);
updateInput();
});

Categories

Resources