How to get checked checkbox inside in div using jquery? - javascript

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

Related

Adding more value to class to filter

This is my main script, that filters div by checkboxes
function change(){
var checkboxes = document.getElementsByClassName('checkbox');
var chekboxInputs = Array.from(checkboxes).map(a => a.querySelector('input'));
var allAreUnselected = chekboxInputs.every(function(elem){
return !elem.checked;
});
if(allAreUnselected){
chekboxInputs.forEach(function(input){
Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(item){
item.style.display = 'block';
});
});
}
else {
chekboxInputs.forEach(function(input){
Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(item){
item.style.display = input.checked ? 'block' : 'none';
});
});
}
}
change();
This is my html file. In this html there are checkboxes and dives
<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada" onchange="change()"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china" onchange="change()"/>China</label>
</div>
</div>
<div class="result">
<div class="canada">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china">
<h1>China</h1>
<h2>Ni</h2>
</div>
</div>
But the script filters only one value(in my case - city). How can I add another filters to class of div. For example
<div class="checkbox">
<label><input type="checkbox" rel="india" onchange="change()"/>India</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="programming" onchange="change()"/>Programming</label>
</div>
by the adding another value to class
<div class="india programming">...</div>
Adding multiple CSS classes could work, but your current code will overwrite a previous setting of style.display making it sometimes go from none to block, even though the none setting was the right setting.
Here is the code you could use, based on the first example you gave, and an additional result that has both classes "canada" and "china":
function change(){
let results = Array.from(document.querySelectorAll('.result > div'));
// Hide all results
results.forEach(function (result) {
result.style.display = 'none';
});
// Filter results to only those that meet ALL requirements:
Array.from(document.querySelectorAll('.filter input[rel]:checked'), function (input) {
const attrib = input.getAttribute('rel');
results = results.filter(function (result) {
return result.classList.contains(attrib);
});
});
// Show those filtered results:
results.forEach(function (result) {
result.style.display = 'block';
});
}
change();
<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada" onchange="change()"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china" onchange="change()"/>China</label>
</div>
</div>
<div class="result">
<div class="canada">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china">
<h1>China</h1>
<h2>Ni</h2>
</div>
<div class="canada china">
<h1>China and Canada</h1>
<h2>Ni Jason</h2>
</div>
</div>
Note that I assume the rel attribute can only reference one CSS class.

How can I get parrent div data-id

I have
<div class="answers-form" data-id="1">
<div class="form-group">
<label>
<input value="" type="checkbox" name="answer[]">
</label>
</div>
<span></span>
</div>
I need to check, if input is checked, then get div's data-id.
You need to attach a change eventlistener to the checkbox, then get the parent using closest() and finally the data-attribute using data() like :
$('[name="answer[]"]').on('change', function() {
if ( $(this).is(':checked') ) {
console.log( $(this).closest('.answers-form').data('id') );
}
});
If you have to check if the the checkbox is checked on submit you could do this inside the submit event like:
$('form').on('submit', function(e) {
e.preventDefault();
if ( $('[name="answer[]"]').is(':checked') ) {
console.log( 'submit' );
} else {
console.log( 'Prevent submit' );
return false;
}
});
Hope this helps.
$('[name="answer[]"]').on('change', function() {
if ($(this).is(':checked')) {
console.log($(this).closest('.answers-form').data('id'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="answers-form" data-id="1">
<div class="form-group">
<label>
<input value="" type="checkbox" name="answer[]" />
</label>
</div>
<span></span>
</div>
$('input[type="submit"]').on( "click", function(e) {
e.preventDefault();
if( $( "input=[name='answer[]']" ).is(":checked") === true ) {
var data_id = $( ".answers-form" ).attr( "data-id" );
}
});
$(document).ready(function() {
$('[name="answer[]"]').on("change",function(){
if($(this).is(':checked')){
console.log($(".answers-form").attr("data-id"))
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="answers-form" data-id="1">
<div class="form-group">
<label>
<input value="" type="checkbox" name="answer[]">
</label>
</div>
<span></span>
</div>

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.

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

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