Checking all immediate child checkboxes onclicking parent checkbox using JQuery - javascript

I have a list in my html code where onclick of parent checkbox, the immediate child checkboxes should be checked.
<ul class="test_ex">
<li>
<input type="checkbox" id="chckBox" class="parent" onchange="fnTest(this);" /> <a class="ref">Fruits</a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref"> Apple </a>
</li>
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref"> Orange </a>
</li>
</ul>
<ul class="test_ex_sample">
<li>
<input type="checkbox" id="chckBox" class="parent" onchange="fnTest(this);" /> <a class="ref">Birds</a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref"> Peacock </a>
</li>
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref">Parrot </a>
</li>
</ul>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="parent" onchange="fnTest(this);" /> <a class="ref"> Food </a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref">Bread </a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
I tried many ways to check only the immediate children. But none of them worked.
These are few ways:
Tried using .siblings() [Found this solution on stackoverflow only]
function fnTest(check) {
if ($(check).is(':checked')) {
$(check).siblings('.example').find('.child').attr("checked", true);
} else {
$(check).siblings('.example').find('.child').attr("checked", false);
}
}
Fiddle demo 1
Here the first list works properly. Again when clicked on second list it checks the 3rd list children too.
Secondly tried this set of code
Tried using the class which is checked annd getting children from that class. This checks all parents that belong to that class.
Fiddle demo 2
function fnTest(check) {
if ($(check).is(':checked')) {
var classParent = "." + $(check).attr('class');
$(classParent).attr("checked", true);
}
}
It would be great if someone could point out my mistake.

From your first try of using siblings(). You can change to the following:
function fnTest(check){
if($(check).is(':checked')){
$(check).siblings('.example:first').find('.child').prop("checked",true);
}
else{
$(check).siblings('.example:first').find('.child').prop("checked",false);
}
}
By using this it checks only the first children. And also change your .attr to .prop
here is a demo : Fiddle

You can do this by using jQuery. First of all remove onchange="fnTest(this);" from parent checkbox. Bind change event for parent checkbox like below :
$(function(){
$('.parent').click(function(){
$(this).parent().find('.example:first .child').prop('checked',$(this).is(':checked'));
});
});
Demo

try
function fnTest(check) {
$(check).closest("ul").find(":checkbox").prop("checked",check.checked);
}
DEMO
If you want only direct children use like this
function fnTest(check) {
$(check).closest("li").find(".example:first").find(":checkbox").prop("checked", check.checked);
}
DEMO
NOTE : use latest version in jquery, and also id should be unique

// OK tested
$(document).ready(function(e) {
$('input[type=checkbox]').click(function () {
$(this).parent().find('li input[type=checkbox]').prop('checked', $(this).is(':checked'));
var sibs = false;
$(this).closest('ul').children('li').each(function () {
if($('input[type=checkbox]', this).is(':checked')) sibs=true;
})
$(this).parents('ul').prev().prop('checked', sibs);
});});

Related

Remove and re-add Class Attribute inside a <div> unordered list item

This is the answer as i was able to solve.
Wanted to change the css class="jsTree-clicked" after the button click event happened from Hyperlink1 to Hyperlink3.
$(document).ready(function () {
//remove Class
$('#myJSTree').find('.jsTree-clicked').removeClass('jsTree-clicked');
//need to do add it to List Item which has Id =3
//check the list item which has id =3 if so add the class to it
// It is not a button click event.
$('#myJSTree li').each(function (i, li) {
console.log('<li> id =' + $(li).attr('id'));
var myIdVal = $(li).attr('id');
if (myIdVal == 3) {
$(this).addClass('jsTree-clicked');
}
});
});
.jsTree-clicked { background-color:red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myJSTree">
<ul class="nav nav-list">
<li id="1">
<a class="jsTree-clicked" title="Hyperlink1">HyperLink1</a>
</li>
<li id="2">
<a title="Hyperlink2">HyperLink2</a>
</li>
<li id="3">
<a title="Hyperlink3">HyperLink3</a>
</li>
</ul>
</div>
When the Hyperlink is clicked the JsTree adds a class="jsTree-clicked" . When you navigate to a different node it will remove and re-add the same class to the navigated node.
Expected
I want a function to remove [class="jsTree-clicked"] for the given List Item based on ID inside the div.
AND
Re-add [class="jsTree-clicked"] to any ListItem by passing the Key i.e ID .
I hope I was able to explain my problem.
Thank you
My JSTree is a third party open source.
$('.nav-list').on('click', 'li', function() {
$('.nav-list li.active').removeClass('active');
$(this).addClass('active');
});
.active{
background-color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myJSTree">
<ul class="nav nav-list">
<li id="1">
<a title="Hyperlink1">HyperLink1</a>
</li>
<li id="2">
<a title="Hyperlink2">HyperLink2</a>
</li>
<li id="3">
<a title="Hyperlink3">HyperLink3</a>
</li>
</ul>
</div>
Maybe this is helpful to you?
$(function () { $('#myJSTree').jstree(); });
const toggle = (e) => {
if (+$("#test").val()>=10 ) {
e.target.classList.remove("jstree-clicked");
console.log("You entered an invalid number.")
}
console.log(e.target)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<div id="myJSTree">
<ul>
<li id="1">
<a title="Hyperlink1" onclick="toggle(event)">HyperLink1</a>
</li>
<li id="2">
<a title="Hyperlink2">HyperLink2</a>
</li>
<li id="3">
<a title="Hyperlink3">HyperLink3</a>
</li>
</ul>
</div>
<input type="text" value="3" id="test"> < 10
I have simply included a rudimentary toggle() function to demonstrate the point of removing and ading the class name "jsTree-clicked". Please note that JStree assigns other classes to the node dynamically that should be kept there.
It appears to me as if the class jstree-clicked (not: jsTree-clicked) is set by JSTree after an element was clicked. You might have to play aroud with this further to get what you want.
The following might be more what you want. It will "link" to the given href only when the predefined test criteria in checkinput() is met:
$(function () { $('#myJSTree').jstree(); });
const checkinput = (e) => {
if (+$("#test").val()>=10 ) {
console.log("You entered an invalid number.")
} else document.location.href=e.target.href;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<div id="myJSTree">
<ul>
<li id="1">
<a title="Hyperlink1" href="https://jsonplaceholder.typicode.com/users/1" onclick="checkinput(event)">HyperLink1</a>
</li>
<li id="2">
<a title="Hyperlink2" href="https://jsonplaceholder.typicode.com/users/2">HyperLink2</a>
</li>
<li id="3">
<a title="Hyperlink3">HyperLink3</a>
</li>
</ul>
</div>
<input type="text" value="3" id="test"> < 10<br>
HyperLink1 will link to the page "user1" if the input is valid, <br>otherwise an eror will be shown in the console.

Use li to select radio input buttons?

I am creating a payment option buttons. The problem is the pre-made option gives no place to add payment images and descriptions. So I have made a (li) list of options using basic html and content now i want to know if we can make li to select input when pressed
HTML Code
<div class="shipping-method">
<ul class="">
<li>
<div class="item">Wechat
<div class="disc"></div>
</div>
</li>
<li>
<div class="item on">AliPay
<div class="disc">Discription goes here</div>
</div>
</li>
</ul></div>
Current Input Code
<div class="radio-buttons-selection">
<label>
<input name="shipping" type="radio" class="radio" id="shipping_{$shipping.shipping_id}" value="{$shipping.shipping_id}" {if $order.shipping_id eq $shipping.shipping_id}checked="true" {/if} supportCod="{$shipping.support_cod}" insure="{$shipping.insure}" onclick="selectShipping(this)">
<div class="shipping_{$shipping.shipping_id} box"> <span>{$shipping.shipping_name}</span> </div>
</label>
I'm unfortunately not quite sure how you have implemented your Current input code with the rest of the code. However, using the first snippet of code, something like this (using jQuery) should work:
$("li").on("click", function() {
$("input[type=radio]").each(function() {
$(this).prop("checked", false);
});
$(this).find("input[type=radio]").prop("checked", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="shipping-method">
<ul class="">
<li>
<div class="item">Wechat
<div class="disc"></div>
<input type="radio"/>
</div>
</li>
<li>
<div class="item on">AliPay
<div class="disc">Discription goes here</div>
<input type="radio"/>
</div>
</li>
</ul></div>
Basically, if a list-item is clicked, find the input[type=radio] in that list item and check it (and before that, make sure all others are unchecked so we keep it 'valid').
If you can merge your HTML code with your Current input code I might be able to provide a better example, but nonetheless you might see what's going on and what you could do?
$(".shipping-method li").on("click", function() {
$(".shipping-method input[type=radio]").each(function() {
$(this).prop("checked", false);
$(this).children(".shipping-method .item").removeClass("on");
});
$(this).find("input[type=radio]").prop("checked", true);
$(this).find(".item").addClass("on");
});
[:I assume the 'selectShipping' method will try to extract above
values(id,value,insure,supportCod) from 'this']
'Right Click' on browser & find out the following in run time the respective values for input element '*' that you are not able to customize:
1.)$shipping.shipping_id=?? , value=??,supportCod=??,insure=?? Of first option
2.)$shipping.shipping_id=?? , value=??,supportCod=??, insure=?? Of second option
elements into elements containin as the selectShipping method expects it to be
-->
<div class="shipping-method">
<ul class="">
<li>
<div class="item"><a href="javascript:;" class="weixin_wap" id="shipping_{$shipping.shipping_id_Of_firstoption}" value="{??Of_firstoption}" insure="{$shipping.insureOf_firstoption}" onclick="selectShipping(this)>Wechat</a>
<div class="disc"></div>
</div>
</li>
<li>
<div class="item on"><a href="javascript:;" class="alipaywap" id="shipping_{$shipping.shipping_id_Of_second_option}" value="{??Of_second_option}" insure="{$shipping.insureOf_second_option}" onclick="selectShipping(this)>AliPay</a>
<div class="disc">Discription goes here</div>
</div>
</li>
</ul></div>

problems with nav in mobile view

I am trying to have an icon that is going to show up in my mobile veiw where you can click show and hide the menu,
right now my code doesnt work, it does not open at all
my problem is trying to figure out id's and inputs here
not sure what I am doing wrong, could someone point me to the right direction please ? Thanks in advance
//this is what I have
<nav class="navMenu">
<input id="menu-icon" type="checkbox">
<label id="menu-icon" class="iconMenuLbl" for="menu-icon"></label>
<ul>
<li>
<img class="navImg" src="media/Home-tall.png" alt="">
</li>
<li>
<img class="navImg" src="media/My-Details-tall.png" alt="">
</li>
<li>
<img class="navImg" src="media/My-Loans-tall.png" alt="">
</li>
<li id="loggedin-box" class="">
<form method="POST" action="login">
<div>
<strong>some name</strong>
</div>
<button style="padding:0px;" name="logout" type="submit">
<img class="navImg" src="media/Sign-Out.png">
</button>
</form>
</li>
</ul>
</nav>
//js file
$(function() {
var menuVisible = false;
$('#menu-icon').click(function() {
if (menuVisible) {
$('.navMenu').css({'display':'none'});
menuVisible = false;
return;
}
$('.navMenu').css({'display':'block'});
menuVisible = true;
});
$('.navMenu').click(function() {
$(this).css({'display':'none'});
menuVisible = false;
});
});
You have two ids sharing the same name. 'menu-icon' try changing one of the ids to another name. IDs should be unique. -- ALSO move your input field out of the nav tag.

How to prevent Jquery click event?

am using Html and Jquery in my Project
Project Demo jsfiddle here
I have <ul> radio buttons in my HTML page as below
HTML Code
<ul class="featureBoxes paddingRight">
<li class="featuresHeading features liListTo">
<input type="radio" id="selectProvider" class="rd" name="rdbToList" value="1" />
<label for="selectProvider">
Radio 1
</label>
</li>
<li>
<ul class="featureListings ">
<li>
data 1
</li>
</ul>
</li>`
<li class="featuresHeading options liListTo">
<input type="radio" id="selectPatient" class="rd" name="rdbToList"
value="2" />
<label for="selectPatient">
Radio 2
</label>
</li>
<li>
<ul class="featureListings">
<li>
<div id="sptDiv" style="padding: 2px 0px 2px 8px;">
Data 2
</div>
</li>
</ul>
</li>
<li class="featuresHeading curtain-options liListTo">
<input type="radio" id="directEmail" class="rd" name="rdbToList"
value="3">
<label for="directEmail">
Radio 3
</label>
</li>
<li>
<ul class="featureListings ">
<li>
Data 2
</li>
</ul>
</li>
</ul>
and I am using Jquery for this to slideup and slide down.
Problem: when I click on radio buttons lable it slidedown for few seconds and again slideup as in above fiddle.
JavaScript
$(function () {
$("ul.featureListings").hide();
$(".featuresHeading").click(function (event) {
$(this).find('.rd').attr('checked', 'checked');
if ($(this).find('.rd').is(':checked')) {
$('ul.featureListings.demo').slideUp(300);
$(this).find('.rd').attr('checked', 'checked');
$('ul.featureListings.demo').not($(this).next().find('ul.featureListings')).removeClass("demo");
if ($(this).next().find('ul.featureListings').hasClass("demo")) {
$(this).next().find('ul.featureListings').removeClass("demo");
$(this).next().find('ul.featureListings').slideUp(300);
}
else {
$(this).next().find('ul.featureListings').addClass("demo");
$(this).next().find('ul.featureListings').slideDown(300);
}
}
//event.preventDefault();
return true;
});
});
Please give me suggestion how to prevent click event on <ul> and radio buttons ?
JSFiddle here
try
$("ul.featureListings").hide();
$(".featuresHeading [type=radio]").click(function (e) {
$("ul.featureListings").slideUp();
$(this).parent().next("li").find("ul").stop().slideDown(300);
});
NOTE: change click event to radio button not container. If you bind click event on container The click event call two times when using label for with radio button :example.check when name is clicked ,
DEMO
Use .prop('checked', true) instead of .attr('checked', 'checked') and dont handle "click" events from <label>. Example
$(function () {
$("ul.featureListings").hide();
$(".featuresHeading").click(function (event) {
if (event.target !== this && !$(event.target).is('input')) {
return;
}
$(this).find('.rd').prop('checked', true);
if ($(this).find('.rd').is(':checked')) {
$('ul.featureListings.demo').slideUp(300);
$(this).find('.rd').prop('checked', true);
$('ul.featureListings.demo').not($(this).next().find('ul.featureListings')).removeClass("demo");
if ($(this).next().find('ul.featureListings').hasClass("demo")) {
$(this).next().find('ul.featureListings').removeClass("demo");
$(this).next().find('ul.featureListings').slideUp(300);
}
else {
$(this).next().find('ul.featureListings').addClass("demo");
$(this).next().find('ul.featureListings').slideDown(300);
}
}
});
});

duplicate functions, how may I combine them?

I have a function that remains pretty much constant except for the changing class names. I was hoping to make the code a little less text heavy. How may I go about making it just a small function instead of repeating it n times. My concern is also about removing the active class for the last li that was clicked. I've provided only 2 instances here, but this code is repeated n number of times.Any ideas would be much appreciated.
$('a.app1-preview').click(function() {
//remove last active classes
$(".app2").removeClass('active');
$(".app2-preview").removeClass('active');
//Add active class for this
$(this).parent().addClass('active');
$(this).addClass('active');
$('.app-preview-2').fadeOut("slow", function () {
$('.app-preview-1').fadeIn("slow");
});
});
$('a.app2-preview').click(function() {
//remove last active classes
$(".app1").removeClass('active');
$(".app1-preview").removeClass('active');
//Add active class for this
$(this).parent().addClass('active');
$(this).addClass('active');
$('.app-preview-1').fadeOut("slow", function () {
$('.app-preview-2').fadeIn("slow");
});
});
HTML code:
<div class="app-container">
<ul class="apps">
<li class="app1">
<a title href="#" class="app1-preview blocklink">
<span>ANOTHER<br /> APP</span>
</a>
</li>
<li class="app2">
<a title href="#" class="app2-preview blocklink">
<span>SECOND<br /> APP</span>
</a>
</li>
</div>
Try to exploit the fact that you have .active class. ;) Preview - http://jsfiddle.net/evSqF/1/
js:
<script>
$('a.blocklink').click(function() {
var self = $(this);
$('.active').fadeOut('slow', function(){
$(this).removeClass('active');
self.fadeIn('slow');
self.addClass('active');
});
});
</script>
html:
<div class="app-container">
<ul class="apps">
<li class="app1">
<a title href="#" class="app1-preview blocklink">
<span>ANOTHER<br /> APP</span>
</a>
<div class="app-preview active">App1 preview</div>
</li>
<li class="app2">
<a title href="#" class="app2-preview blocklink">
<span>SECOND<br /> APP</span>
</a>
<div class="app-preview">App2 preview</div>
</li>
</ul>
</div>
Edit: After I got some caffeine, I noticed the problems with the setup. I've created a demo at JSFiddle. The markup will display a "header" for an app which will display the child description when clicked on, and hide the descriptions of other sibling's descriptions.
In this case, you can show the current element, and hide the siblings, which would be a cleaner solution as it scales as you at more app elements.
$(".app").click(function() {
var $self = $(this);
var $apps = $self.closest(".apps");
var $selfSiblings = $apps.children(".app").not($self);
$self.addClass(".active");
$self.find(".app-preview").addClass("active");
$selfSiblings.removeClass(".active");
$selfSiblings.find(".app-preview").removeClass("active").fadeOut("slow", function() {
$self.find(".app-preview").fadeIn("slow");
});
});​
I would also recommend rewriting your HTML as such:
<div class="app-container">
<ul class="apps">
<li class="app">
App 1<br />
<a title href="#" class="app-preview blocklink">
<span>PREVIEW 1</span>
</a>
</li>
<li class="app">
App 2<br />
<a title href="#" class="app-preview blocklink">
<span>PREVIEW 2</span>
</a>
</li>
<li class="app">
App 3<br />
<a title href="#" class="app-preview blocklink">
<span>PREVIEW 3</span>
</a>
</li>
</div>​
Write a function to make the functions for you:
function makeHandler(deactivate, fadeOut, fadeIn) {
return function() {
//remove last active classes
$(deactivate).removeClass('active');
//Add active class for this
$(this).parent().addClass('active');
$(this).addClass('active');
$(fadeOut).fadeOut("slow", function () {
$(fadeIn).fadeIn("slow");
});
});
Then:
$('a.app1-preview').click(makeHandler('.app2, .app2-preview', '.app-preview-2', '.app-preview-1'));
$('a.app2-preview').click(makeHandler('.app1, .app1-preview', '.app-preview-1', '.app-preview-2'));
You could probably simplify things further by re-thinking the naming conventions you've got.
I would suggest to define a single function:
function single(index_main, index_aux) {
// Does all your magic
}
$('a.app1-preview').click(function() {
single("1", "2");
});
$('a.app2-preview').click(function() {
single("2", "1");
});
And that does the trick.
I made a jsfiddle example for you. Have a look at it here, it uses as much code that you wrote as possible, so nothing that should surprise you will be there :)
http://jsfiddle.net/2ZPxx/
Basically I ended up with this HTML:
<div class="app-container">
<ul class="apps">
<li class="app1">
<a title href="#" class="app1-preview blocklink" id="app1">
<span>ANOTHER<br /> APP</span>
</a>
</li>
<li class="app2">
<a title href="#" class="app2-preview blocklink" id="app2">
<span>SECOND<br /> APP</span>
</a>
</li>
</div>
<div class="app-preview-app1 app-preview">App1 preview</div>
<div class="app-preview-app2 app-preview">App2 preview</div>
And this javascript:
$('.apps li a').click(function() {
var id = $(this).attr('id');
$('.apps li').removeClass('active');
//Add active class for this
$(this).parent().addClass('active');
$(this).addClass('active');
$('.app-preview').fadeOut("slow", function () {
$('.app-preview-'+id).fadeIn("slow");
});
});

Categories