How to use JQuery find and each together? [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I am printing row column table. In each of my column items have 2 checkbox,
<?php
for($b=0; $b<$RoomSize["COL"]; $b++){
?>
<div class="col">
<?php
$ColKeyExist = checkIfKeyExist($GetSeatLayout, $b, 2);
if($RowKeyExist){
if($ColKeyExist){
if($GetSeatLayout[$a]["ROWID"]==$a && $GetSeatLayout[$a]["COLUMNID"]==$b){
?>
<div id=<?=$a.",".$b?>>
<div class="form-check pl-0">
<input class="form-check-input" type="checkbox" name="SEATNO" value=<?=$a.",".$b?>>
<label class="fas fa-chair SEATIMAGE"></label>
<input class="form-check-input" type="checkbox" name="SEATSTATUS" value=0 >
</div>
</div>
</div>
<?php
}
}
}
?>
This is my JQUERY code. I try following the documentation but failed to achieve output
$(".col").click(function (e) {
$(this).find('input[type="checkbox"]').each(function (a) {
$(this).prop('checked', "checked");
});
});
When on click on the particular ".col" i want it to find all checkbox under it and check them,

Try this
$('.col input[type=checkbox]').each(function (){
//use one of the below
$(this).prop('checked', true);
$(this).attr('checked', true); // if your jQuery 1.5.x and below
});

You need some modification over there, see below snippet:
$(document).ready(function(){
$(".col").click(function (e) {
let col = $(this); // This line ensure you get outer scope where you clicking.
col.find('input[type="checkbox"]').each(function (a) {
col.find('input[type="checkbox"]').eq(a).prop('checked', "checked");
});
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<div id="col-1">
<div class="form-check pl-0">
<input class="form-check-input" type="checkbox" name="SEATNO">
<label class="fas fa-chair SEATIMAGE"></label>
<input class="form-check-input" type="checkbox" name="SEATSTATUS" value="0">
</div>
</div>
</div>
<div class="col">
<div id="col-2">
<div class="form-check pl-0">
<input class="form-check-input" type="checkbox" name="SEATNO" value="0">
<label class="fas fa-chair SEATIMAGE"></label>
<input class="form-check-input" type="checkbox" name="SEATSTATUS" value="0">
</div>
</div>
</div>
Or if you don't want iterate the checkbox and just checked them all inside .col then just you don't need trigger .each function you can simply write your code following way:
$(".col").click(function (e) {
$(this).find('input[type="checkbox"]').prop('checked', "checked");
});

$(document).ready(function () {
$(".col").click(function (e) {
console.log("success");
$(this).find('input[type="checkbox"]').each(function (a) {
var isChecked = $(this).prop('checked');
if(isChecked == true){
$(this).prop('checked', false);
}else if(isChecked == false){
$(this).prop('checked', true);
}
});
});
});

Related

Bootstrap checkbox buttons not changing state

I used to have radio buttons, but I changed the script to use bootstrap checkboxes. But it is not changing the state when using bootstrap switches.
This is snippet of my code:
<div class="form-group">
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="upd_active" class="updactive" id="upd_yes" value="1" checked> Yes </label>
<label class="radio-inline">
<input type="radio" name="upd_active" class="updactive" id="upd_no" value="0"> No </label>
</div>
</div>
<script>
function action(){}
var parentflag = $('#upd_yes').parents('.form-group');
parentflag.find('span').removeClass('checked');
if(is_active == "1"){
$("#upd_no").attr('checked', false);
$("#upd_yes").attr('checked', true);
$('#upd_yes').parent().addClass('checked');
}
else{
$("#upd_yes").attr('checked', false);
$("#upd_no").attr('checked', true);
$('#upd_no').parent().addClass('checked');
}
}
</script>
<div class="form-group">
<label class="col-md-3 control-label">IsActive<span class="text-danger">*</span></label>
<div class="col-md-8">
<input type="checkbox" name="upd_active" class="make-switch updactive" id="upd_yes" value="1" checked>
</div>
</div>
<script>
function action(){
var parentflag = $('#upd_yes').parents('.form-group');
parentflag.find('span').removeClass('checked');
if(is_active == "1"){
$("#upd_yes").attr("checked",true);
$('#upd_yes').parent().addClass('checked');
}
else{
$("#upd_yes").attr("checked",false);
$('#upd_yes').parent().removeClass('checked');
}
}
</script>
How can I fix this?
Am able to find 2 issues(actually not issues) as below
is_active is not declared so you cannot check it with if statement
Most importantly your action() function not at all initiated.
So i added below code and updated the snippet.
var is_active = 0;
action();
var is_active = 0;
action();
function action() {
var parentflag = $('#upd_yes').parents('.form-group');
parentflag.find('span').removeClass('checked');
if (is_active == "1") {
$("#upd_yes").attr("checked", true);
$('#upd_yes').parent().addClass('checked');
} else {
$("#upd_yes").attr("checked", false);
$('#upd_yes').parent().removeClass('checked');
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="col-md-3 control-label">IsActive<span class="text-danger">*</span></label>
<div class="col-md-8">
<input type="checkbox" name="upd_active" class="make-switch updactive" id="upd_yes" value="1" checked>
</div>
</div>

jQuery add and remove class based on radio checked value

SOLVED - Thank you all for your time
I'm having a little trouble getting this one right. Basically I have two radio buttons with different values and I need to add and remove the class "active" from div's that pertain to the value of the radio button. See my code below:
HTML:
<li class="field">
<label>choose option:</label>
<label class="radio toggle" gumby-trigger="#phone" for="phoneOrWeb">
<input name="phoneOrWeb" id="phoneOrWeb" value="phone" type="radio">
<span></span> <strong>Phone</strong>
</label>
<label class="radio toggle" gumby-trigger="#web" for="phoneOrWeb">
<input name="phoneOrWeb" id="phoneOrWeb" value="web" type="radio">
<span></span> <strong>Web</strong>
</label>
</li>
<!-- Phone SUB -->
<div class="drawer" id="phone">
<?php include ('formD.php'); ?>
</div>
<!-- /Phone SUB -->
<!-- WEB SUB -->
<div class="drawer" id="web">
<?php include ('formE.php'); ?>
</div>
<!-- /WEB SUB -->
Jquery I attempted:
$("input[name=phoneOrWeb]:radio").click(function () {
if ($('input[name=phoneOrWeb]:checked').val() == "phone") {
$('#web').removeClass('active');
$('#phone').addClass('active');
} else if ($('input[name=phoneOrWeb]:checked').val() == "web") {
$('#web').addClass('active');
$('#phone').removeClass('active');
}
});
Your code is very close. First of all, IDs should always be unique. One element per ID on a page. phoneOrWeb is used twice which is not good. Secondly, if you don't want to do a second jQuery selection, you can just grab the value from the target of the event. This code should work as you expected.
$("input[name=phoneOrWeb]:radio").click(function(ev) {
if (ev.currentTarget.value == "phone") {
$('#web').removeClass('active');
$('#phone').addClass('active');
} else if (ev.currentTarget.value == "web") {
$('#web').addClass('active');
$('#phone').removeClass('active');
}
});
.drawer {
width: 100px;
height: 100px;
background-color: green;
margin: 4px;
}
.drawer.active {
border: 3px solid red;
margin: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="field">
<label>choose option:</label>
<label class="radio toggle" gumby-trigger="#phone" for="phoneInput">
<input name="phoneOrWeb" id="phoneInput" value="phone" type="radio">
<span></span> <strong>Phone</strong>
</label>
<label class="radio toggle" gumby-trigger="#web" for="webInput">
<input name="phoneOrWeb" id="webInput" value="web" type="radio">
<span></span> <strong>Web</strong>
</label>
</li>
<!-- Phone SUB -->
<div class="drawer" id="phone">
Phone!
<!--<?php include ('formD.php'); ?>-->
</div>
<!-- /Phone SUB -->
<!-- WEB SUB -->
<div class="drawer" id="web">
Web!
<!--<?php include ('formE.php'); ?>-->
</div>
<!-- /WEB SUB -->
$("input[name=phoneOrWeb]:radio").change(function () {
if ($(this).val() == "phone") {
$('#web').removeClass('active');
$('#phone').addClass('active');
} else if ($(this).val() == "web") {
$('#web').addClass('active');
$('#phone').removeClass('active');
}
});
Use the change event on the input. The below works.
$("input[name=phoneOrWeb]").change(function () {
if (this.value == "phone") {
$('#web').removeClass('active');
$('#phone').addClass('active');
} else if (this.value == "web") {
$('#web').addClass('active');
$('#phone').removeClass('active');
}
});
Fiddle: https://jsfiddle.net/04uhjuvc/
PS: ids should be unique, you have the same id in both the radio buttons.
You shoud check this one.
How to use radio on change event?
$(document).ready(function() {
$('input[type=radio][name=bedStatus]').change(function() {
if (this.value == 'allot') {
alert("Allot Thai Gayo Bhai");
}
else if (this.value == 'transfer') {
alert("Transfer Thai Gayo");
}
});
});
This depends that the Values of your Radios are equal to the target-element IDs:
$(".radio.toggle").on("click", function() {
$(".drawer").removeClass("active");
$("#"+$(this).val()).addClass("active");
});
You can make use of JQuery toggleClass for this to make it more simple:
$("input[name=phoneOrWeb]:radio").click(function () {
if (this.value == "phone")) {
$('#phone').toggleClass( "active" );
} else if (this.value == "web")) {
$('#web').toggleClass( "active" );
}
});
Try this:
<li class="field">
<label>choose option:</label>
<label class="radio toggle" gumby-trigger="#phone" for="phone-option">
<input id="phone-option" name="phoneOrWeb" value="phone" type="radio">
<span></span> <strong>Phone</strong>
</label>
<label class="radio toggle" gumby-trigger="#web" for="web-option">
<input id="web-option" name="phoneOrWeb" value="web" type="radio">
<span></span> <strong>Web</strong>
</label>
</li>
<div class="drawer" id="phone">phone</div>
<div class="drawer" id="web">web</div>
jQuery script:
<script>
$(document).ready(function () {
$('#phone-option').click(function () {
$('#web').removeClass("active");
$('#phone').addClass("active");
});
$('#web-option').click(function () {
$('#phone').removeClass("active");
$('#web').addClass("active");
});
});
</script>

All / none checkbox

Why doesn't this "All / none" option do his job? I can't see why .attr('checked', status); doesn't toggle all the checkboxes.
And what's the most clever way to hide / show elements of #main belonging to selected categories?
$('input[name="all"]').click(function() {
var status = $(this).is(':checked');
alert(status);
$('input[type="checkbox"]').attr('checked', status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label>
<input type="checkbox" name="all" checked="true">
All / none
</label>
<label>
<input type="checkbox" name="cat1" checked="true">
A
</label>
<label>
<input type="checkbox" name="cat2">
B
</label>
<label>
<input type="checkbox" name="cat3">
C
</label>
<label>
<input type="checkbox" name="cat4">
D
</label>
Use .prop() not .attr()
See http://api.jquery.com/prop/
$('input[name="all"]').click(function(){ var status = $(this).is(':checked'); alert(status); $('input[type="checkbox"]').prop('checked', status); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label><input type="checkbox" name="all" checked="true">All / none</label>
<label><input type="checkbox" name="cat1" checked="true">A</label>
<label><input type="checkbox" name="cat2">B</label>
<label><input type="checkbox" name="cat3">C</label>
<label><input type="checkbox" name="cat4">D</label>
As mentioned here, you should make use of jQuery's .prop() function for checking/unchecking checkbox elements.
So try to change your handler like so:
$('input[name="all"]').click(function(){
var status = !!$(this).prop('checked');
alert(status);
$('input[type="checkbox"]').prop('checked', status);
});
To hide/show elements, I recommend iterating over each one:
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('name');
var status = !!$(this).prop('checked');
if (status) {
$('#main').find('.' + name).show();
} else {
$('#main').find('.' + name).hide();
}
});
Regarding your last question for coloring, I'd recommend using a class, say for example gray.
var total = $('input[type="checkbox"]').not('[name=all]').length;
var count = $('input[type="checkbox"]:checked').not('[name=all]').length;
if (count === total) {
$('input[name="all"]').removeClass('gray');
} else {
$('input[name="all"]').addClass('gray');
}
This sets the checkboxes and the div visibility as needed.
It uses opacity to simulate a grayed-out checkbox.
$('[name="all"]').click(function() { //set all checkboxes to match All / none
$(':checkbox')
.prop('checked', this.checked)
.change();
});
$('input')
.change(function() { //show divs corresponding to checked input
var checked= $(':checkbox:not([name="all"]):checked').length;
$('div.' + this.name)
.toggle(this.checked);
$('[name="all"]')
.prop('checked', checked > 0)
.toggleClass('someChecked', checked && checked<$(':checkbox:not([name="all"])').length);
})
.change(); //run the method immediately
$('[name="all"]').click(function() { //set all checkboxes to match All / none
$(':checkbox')
.prop('checked', this.checked)
.change();
});
$('input')
.change(function() { //show divs corresponding to checked input
var checked= $(':checkbox:not([name="all"]):checked').length;
$('div.' + this.name)
.toggle(this.checked);
$('[name="all"]')
.prop('checked', checked > 0)
.toggleClass('someChecked', checked && checked<$(':checkbox:not([name="all"])').length);
})
.change(); //run the method immediately
.someChecked {
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label>
<input type="checkbox" name="all" checked="true">
All / none
</label>
<label>
<input type="checkbox" name="cat1" checked="true">
A
</label>
<label>
<input type="checkbox" name="cat2">
B
</label>
<label>
<input type="checkbox" name="cat3">
C
</label>
<label>
<input type="checkbox" name="cat4">
D
</label>
// Bind also the single checkboxes to show/hide the elements in div
$('input[type = "checkbox"]').click(function(){
if($(this).prop('checked'))
$('div.' + $(this).attr('name')).show();
else
$('div.' + $(this).attr('name')).hide();
});
$('input[name="all"]').click(function(){
var status = $(this).is(':checked');
alert(status);
$('input[type="checkbox"]').each(function(){
$(this).prop('checked', status);
if(!status)
$('div.' + $(this).attr('name')).hide();
else
$('div.' + $(this).attr('name')).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label><input type="checkbox" name="all" checked="true">All / none</label>
<label><input type="checkbox" name="cat1" checked="true">A</label>
<label><input type="checkbox" name="cat2">B</label>
<label><input type="checkbox" name="cat3">C</label>
<label><input type="checkbox" name="cat4">D</label>
All answers here were great. Just for future reference, I post the one I'll use (which is a mix of #RickHitchcock's and the usage of indeterminate state of a checkbox) :
$('input[name="all"]').click(function() { $(':checkbox').prop('checked', this.checked).change(); });
$('input[type="checkbox"]').change(function() {
var checked = $(':checkbox:not([name="all"]):checked').length;
$('div.' + this.name).toggle(this.checked);
$('input[name="all"]').prop('checked', checked > 0)
.prop('indeterminate', checked && checked < $(':checkbox:not([name="all"])').length);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label><input type="checkbox" name="all" checked>All / none</label>
<label><input type="checkbox" name="cat1" checked>A</label>
<label><input type="checkbox" name="cat2" checked>B</label>
<label><input type="checkbox" name="cat3" checked>C</label>
<label><input type="checkbox" name="cat4" checked>D</label>

How to get checked checkbox inside in div using jquery?

I have list of checkbox inside a div few are checked. i want to change background color green of div when if checkbox is checked.
And On non checked checkbox background color should be gray.
HTML Code :
<div class="row">
<label>
<div class="col s3" style="padding:10px" id="div39">
<div>
<input type="checkbox" name="chk39" value="39" checked="">
<span>Featured Project</span>
</div>
</div>
</label>
<label>
<div class="col s3" style="padding:10px" id="div40">
<div>
<input type="checkbox" name="chk40" value="40">
<span>Specials/Discounts</span>
</div>
</div>
</label>
</div>
Jquery Code:
var check = 1;
$('div').find('input[type=checkbox]').click(function(event) {
var val = $(this).val();
if(check==1)
{
$('#div'+val).css({'background-color': 'lightgreen'});
check=0;
}else{
$('#div'+val).css({'background-color': 'lightgray'});
check=1;
}
});
$(document).ready(function($) {
var selected = [];
$('input[type=checkbox] :checked').each(function() {
alert('asd');
selected.push($(this).attr('value'));
});
});
Use .closest to find the closest element having specified selector.
Use .change listener over check-box elements than click
Use .change() to invoke change-handler initially.
Also consider Number(this.checked), It will be 0 if this.checked ==> false or otherwise.
$('div').find('input[type=checkbox]').change(function(event) {
var color = ['lightgreen', 'lightgray'];
var index = Number(this.checked);
$(this).closest('.s3').css({
'background-color': color[index]
});
}).change();
$(document).ready(function($) {
var selected = [];
$('input[type=checkbox] :checked').each(function() {
selected.push($(this).attr('value'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="row">
<label>
<div class="col s3" style="padding:10px" id="div39">
<div>
<input type="checkbox" name="chk39" value="39" checked="">
<span>Featured Project</span>
</div>
</div>
</label>
<label>
<div class="col s3" style="padding:10px" id="div40">
<div>
<input type="checkbox" name="chk40" value="40">
<span>Specials/Discounts</span>
</div>
</div>
</label>
</div>
you can find the parent div using the closest() method.
$('div').find('input[type=checkbox]').click(function(event) {
var val = $(this).val();
var parent = $(this).closest(".col");
if(this.checked) {
parent.css({
'background-color': 'lightgreen'
});
} else {
parent.css({
'background-color': 'lightgray'
});
}
});
Fiddle
$('div').find('input[type=checkbox]').click(function(event) {
if($(this).is(':checked'))
{
$(this).closest('div').css({'background-color': 'lightgreen'});
}
else
{
$(this).closest('div').css({'background-color': 'lightgray'});
}
});
$(document).ready(function($) {
var selected = [];
$('input[type=checkbox]').not(':checked').closest('div').css({'background-color': 'lightgray'});
$('input[type=checkbox]:checked').closest('div').css({'background-color': 'lightgreen'});
});
Below is the updated fiddle
https://jsfiddle.net/cc3q2axr/
This is how I would do it:
$("input[type='checkbox']").click(function() {
if ($(this).prop("checked") === true) {
$(this).closest(".col").css("background-color", "#36ac3b");
} else {
$(this).closest(".col").css("background-color", "#999");
}
});
Here is the JSFiddle demo

jquery each or custom checkbox question

I have a problem on the result and i'm already tired of solving.
HTML
<input type="checkbox" class="check" checked="checked" />
<input type="checkbox" class="check" />
JQUERY
$.fn.op_checkbox = function() {
$(this).hide();
$(this).wrap('<div class="op_checkbox"></div>');
$(this).parent().append('<div class="op_check_on_off"> </div>');
if($(this).is(':checked')) {
$('.op_check_on_off').addClass('op_check_on');
}
else {
$('.op_check_on_off').addClass('op_check_off');
}
}
$(document).ready(function() {
$('.check').op_checkbox();
});
Result
<div class="op_checkbox">
<input class="check" type="checkbox" checked="checked" style="display: none;">
<div class="op_check_on_off op_check_on"> </div>
</div>
<div class="op_checkbox">
<input class="check" type="checkbox" style="display: none;">
<div class="op_check_on_off op_check_on"> </div>
</div>
The result of first checkbox is copied in 2nd checkbox, the result should be:
<div class="op_checkbox">
<input class="check" type="checkbox" checked="checked" style="display: none;">
<div class="op_check_on_off op_check_on"> </div> <!-- on here -->
</div>
<div class="op_checkbox">
<input class="check" type="checkbox" style="display: none;">
<div class="op_check_on_off op_check_off"> </div> <!-- off here -->
</div>
What is the reason and problem of this? Thanks for your help
I think there are two problems currently in your code. Sangdol helped address the issue that comes with the scoping of $(this), and Shankar helped with the issue of your selector when you are adding the class. http://jsfiddle.net/rkw79/DZYFN/
$('.check').each( function() {
$(this).hide();
$(this).wrap('<div class="op_checkbox"></div>');
$(this).parent().append('<div class="op_check_on_off"> </div>');
if($(this).is(':checked')) {
$(this).parent().find('div').addClass('op_check_on');
}
else {
$(this).parent().find('div').addClass('op_check_off');
}
})
The this inside of function op_checkbox() is array-like jQuery object, so you should process each object with loop like this:
$.fn.op_checkbox = function() {
this.each(function(){
var $this = $(this);
$this.hide()
.wrap('<div class="op_checkbox"></div>')
.parent().append('<div class="op_check_on_off"> </div>');
if($this.is(':checked')) {
$this.parent().find('.op_check_on_off').addClass('op_check_on');
}
else {
$this.parent().find('.op_check_on_off').addClass('op_check_off');
}
});
}
$(document).ready(function() {
$('.check').op_checkbox();
});
And I refactored some code.
Inside of fn function, this is already jQuery object so you don't need to wrap like $(this).
Used jQuery chain.
Cached $(this). This can improve performance(though it's small improvement).
Try this
$.fn.op_checkbox = function() {
$(this).hide();
$(this).wrap('<div class="op_checkbox"></div>');
$(this).parent().append('<div class="op_check_on_off"> </div>');
if($(this).is(':checked')) {
$(this).parent().find('.op_check_on_off').addClass('op_check_on');
}
else {
$(this).parent().find('.op_check_on_off').addClass('op_check_off');
}
}
$(document).ready(function() {
$('.check').op_checkbox();
});

Categories

Resources