jquery each or custom checkbox question - javascript

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

Related

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

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

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

How do I get a <div> on a nearby node in the DOM?

I'm trying to write some JavaScript that could be used throughout my app, and allow a checkbox to show/hide a nearby element.
If I have these elements:
<div class="optionable" style="display: block;">
<div class="row">
<div class="col-md-2">
<input checked="checked" class="form-control"
data-val="true" id="IsActive"
name="IsActive"
onclick="CheckboxOptionsToggle(this);"
type="checkbox" value="true">
</div>
<div class="col-md-8">
Chapter
</div>
</div>
<div class="row options">
<div class="col-md-12">
Some data here...
</div>
</div>
</div>
And this script:
CheckboxOptionsToggle = function (thisCheckbox) {
debugger;
var optionElement = $('.options');
if (thisCheckbox.checked) {
$(thisCheckbox).closest(optionElement).show();
} else {
$(thisCheckbox).closest(optionElement).hide();
}
}
But this isn't working. I would like the checkbox with the onclick="CheckboxOptionsToggle(this);" to trigger the options element in the same optionable div to either show or hide.
What am I doing wrong in my JavaScript/jQuery?
UPDATE: This is my final solution:
$('.optionToggle').on('change', function () {
$(this).closest('.optionable').find('.options').toggle(this.checked);
});
$(document).ready(function () {
var toggleElements = document.body.getElementsByClassName('optionToggle');
for (var i = 0; i < toggleElements.length; i++) {
var thisCheck = $(toggleElements[i]);
thisCheck.closest('.optionable').find('.options').toggle(thisCheck.prop('checked'));
}
});
<div class="optionable" style="display: block;">
<div class="row">
<div class="col-md-2">
<input checked="checked" class="form-control optionToggle"
data-val="true" id="IsActive"
name="IsActive"
type="checkbox" value="true">
</div>
<div class="col-md-8">
Chapter
</div>
</div>
<div class="row options">
<div class="col-md-12">
Some data here...
</div>
</div>
</div>
Be more generic, and stop using inline event handlers
$('[type="checkbox"]').on('change', function() { // or use class to not attach to all
$(this).closest('.optionable').find('.options').toggle(this.checked);
}).trigger('change');
FIDDLE
You can change it like
CheckboxOptionsToggle = function (thisCheckbox) {
debugger;
var optionElement = $('.options');
if (thisCheckbox.checked) {
$(thisCheckbox)..closest('div.optionable').find(optionElement).show();
} else {
$(thisCheckbox)..closest('div.optionable').find(optionElement).hide();
}
}
I would stay away from .closes, because it is so specific, instead I would go with more reusable code like so:
HTML:
<input type="checkbox" id="toggler" data-target-class="some-div" class="toggler" value="myValue" checked> Toggle Me
<div class="some-div">
Some Text within the div.
</div>
JS:
$('#toggler').on('click', function() {
var targetClass = $(this).data('target-class');
$('.' + targetClass).toggle($(this).checked);
});
JSFiddler: https://jsfiddle.net/ro17nvbL/
I am using data element on the checkbox to specifiy which divs to show or hide. This allows me to not only hide/show divs but anything n the page, and not only one instance but as many as needed. Way more flexible - still does the same job.

Disable input if checkbox checked

i want to disable inputs when a checbox is checked.
part of html:
<div class="span1 ">
<div class="control-group" id="niedziela">
<label class="control-label" for="">Niedziela</label>
<div class="controls">
<input type="text" value="<?= $metavalue->nightlife_open_7_start ?>" name="meta[nightlife_open_7_start]" id="nightlife_open_7_start" class="m-wrap span12 timepicker-24" placeholder="">
<input type="text" value="<?= $metavalue->nightlife_open_7_end ?>" name="meta[nightlife_open_7_end]" id="nightlife_open_7_end" class="m-wrap span12 timepicker-24" placeholder="">
<input id="klient_open_4_end" type="checkbox" <?=_ set_checked($metavalue->nightlife_open_7_end,'do ostatniego klienta') ?> value="do ostatniego klienta" name="meta[nightlife_open_7_end]" class="m-wrap span12 timepicker" placeholder=""> Do ost. klienta
<input id="zamkniete_open_4_end" type="checkbox" <?=_ set_checked($metavalue->nightlife_open_7_start,'zamkniete') ?> value="zamkniete" name="meta[nightlife_open_7_start]" class="m-wrap span12 timepicker" placeholder=""> Zamknięte
</div>
</div>
</div>
what i want is that if checkbox with id klient_open_4_end is checked it should disable input with id="nightlife_open_7_end"
if checkbox with id="zamkniete_open_4_end" is checked should disable both inputs text areas
i tried with :
<script type="text/javascript">
$(document).ready(function($) {
$('#klient_open_4_end').change(function() {
$(this).find("#nightlife_open_7_start").attr("disabled", true);
});
});
</script>
You'll need to listen to the click event of the checkboxes. Since you've tagged the question with jQuery too,
$(function(){
$('#klient_open_4_end').on('click', function(){
if($(this).is(':checked')){
$('#nightlife_open_7_start').attr('disabled', true);
} else {
$('#nightlife_open_7_start').attr('disabled', false);
}
});
$('#zamkniete_open_4_end').on('click', function(){
// assuming the textarea is inside <div class="controls /">
if($(this).is(':checked')){
$('.controls input:text, .controls textarea').attr('disabled', true);
} else {
$('.controls input:text, .controls textarea').attr('disabled', false);
}
});
});
Update
You can shorten this even more and use the following instead:
$(function(){
$('#klient_open_4_end').on('click', function(){
$('#nightlife_open_7_start').attr('disabled', $(this).is(':checked'));
});
$('#zamkniete_open_4_end').on('click', function(){
// assuming the textarea is inside <div class="controls /">
$('.controls input:text, .controls textarea').attr('disabled', $(this).is(':checked'));
});
});
This is fairly simple, you can do it like this
$(document).ready(function () {
$('#klient_open_4_end').click(function () {
$('#nightlife_open_7_start').prop('disabled', function(i, v) { return !v; });
});
});
But from your snippet I'm assuming you want to run something when the page loads to disable the input as well, you can do that the same way essentially.
You can achieve this as
$('#chk').change(function(){
if($(this).is(':checked'))
$('#inp1').prop('disabled','disabled')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' id='inp1' />
<input type='text' id='inp2' />
<input type='checkbox' id='chk' />
checkout this simple code
<html>
<body>
<input type="checkbox" id="klient_open_4_end" name="klient_open_4_end"/>
<input type="text" id="nightlife_open_7_end" name="nightlife_open_7_end"/>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#klient_open_4_end").change(function(){
if($(this).prop("checked")){
$("#nightlife_open_7_end").prop("disabled",true);
}
else{
$("#nightlife_open_7_end").prop("disabled",false);
}
});
});
</script>
</html>
In above code
$("#nightlife_open_7_end").prop("disabled",true/false);
you may use
$('#nightlife_open_7_end').attr('disabled', true/false);
It is for onclick disable and enable
<!DOCTYPE html>
<html>
<body>
Checkbox: <input type="checkbox" id="myCheck">
<button onclick="check()">Check Checkbox</button>
<button onclick="uncheck()">Uncheck Checkbox</button>
<script type="text/javascript">
function check() {
if(document.getElementById("myCheck").checked == true)
{
document.getElementById("input").disabled = true;
}
else{
document.getElementById("input").disabled = false;
}
}
</script>
</body>
</html>

Remove input value jquery

each time I click on a option his data-type should appear in the input.
But I want if the value is already in the .val of the input should not appear anymore and if I click twice I want to remove the data-type from input.
Here is my Jsfiddle:
$('.checkbox').on('click', function () {
var type = $(this).data('type'),
answer = $('.answer'),
initial = $('.answer').val();
$(this).toggleClass('checked');
if (answer.val().length === 0) {
answer.val(type);
} else {
answer.val(initial + ',' + type);
}
});
http://jsfiddle.net/xbwocrf3/
Thanks!
One solution is using jquery map:
$('.checkbox').on('click', function() {
$(this).toggleClass('checked');
//save the values of checked in an array
var answerValues = $(".checkbox.checked").map(function() {
return $(this).data("type");
}).get();
//update input text with this values
$(".answer").val(answerValues);
});
.checkbox.checked {
border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="answer" />
<div class="checkbox" data-type="1">Option #1</div>
<div class="checkbox" data-type="2">Option #2</div>
<div class="checkbox" data-type="3">Option #3</div>
<div class="checkbox" data-type="4">Option #4</div>
Do another check before adding the value there:
$('.checkbox').on('click', function () {
var type = $(this).data('type'),
answer = $('.answer'),
initial = $('.answer').val();
$(this).toggleClass('checked');
if (answer.val().length === 0) {
answer.val(type);
} else if (!new RegExp("\,?" + type + "\,?").test(initial)) {
answer.val(initial + ',' + type);
}
});
.checkbox.checked {
border:2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="answer" />
<div class="checkbox" data-type="1">Option #1</div>
<div class="checkbox" data-type="2">Option #2</div>
<div class="checkbox" data-type="3">Option #3</div>
<div class="checkbox" data-type="4">Option #4</div>
Use jQuery's map function to get the type data from all elements. Then combine using the join function.
http://jsfiddle.net/xbwocrf3/8/
$('.checkbox').on('click', function() {
var answer = $('.answer');
$(this).toggleClass('checked');
answer.val( $(".checkbox.checked").map(function() {return $(this).data("type")}).get().join(", ") );
});
This solution is a little cleaner:
http://jsfiddle.net/xbwocrf3/9/ (link updated, I pasted it wrong before)
It uses native checkboxes
Instead of doing something as hard as trying to remove old values, it rewrites the whole value of the input from scratch
The items appear always in their natural order
HTML
<input type="text" class="answer" />
<div>
<input type="checkbox" value="1" name="something" id="something1"/>
<label for="something1">Option #1</label>
</div>
<div>
<input type="checkbox" value="2" name="something" id="something2"/>
<label for="something2">Option #2</label>
</div>
<div>
<input type="checkbox" value="3" name="something" id="something3"/>
<label for="something3">Option #3</label>
</div>
<div>
<input type="checkbox" value="4" name="something" id="something4"/>
<label for="something4">Option #4</label>
</div>
CSS
input[type="checkbox"]{
display: none;
}
input[type="checkbox"]:checked + label{
border:2px solid green;
}
Javascript
$('input[type=checkbox]').on('change', function() {
var $answer = $(".answer");
var checked_values = $.map($("input:checked"), function (element){
return element.value;
});
$answer.val(checked_values);
});
please check fiddle
$('.checkbox').on('click', function () {
$(this).toggleClass('checked');
var typen = '';
$(".checkbox").each(function () {
var type = $(this).data('type');
if ($(this).hasClass('checkbox checked')) {
typen = typen + ',' + type;
}
});
if (typen.length > 0) {
typen = typen.substring(1, typen.length);
}
$('.answer').val(typen);
});
Check if the input has checked class:
if($(this).hasClass('checked'))
return;
Final:
$('.checkbox').on('click', function() {
if($(this).hasClass('checked'))
return;//Stop the execution of the function
var type = $(this).data('type'),
answer = $('.answer'),
initial = $('.answer').val();
$(this).toggleClass('checked');
if(answer.val().length === 0) {
answer.val(type);
} else {
answer.val(initial +','+ type);
}
});

Categories

Resources