Checkbox show img - javascript

I'm trying to make it so, when you checked/uncheck a checkbox, the img appears/disappears. As of now, when I checked a box, all 4 of the images appear instead of just the one. Also I was wondering is it wrong to use document.ready multiple times? This is what I have:
Js:
$(document).ready
(
function()
{
$("#pump").hide();
$("input:checkbox").change(function() {
this.checked?$("#pump").show():$("#pump").hide();
});
});
$(document).ready
(
function()
{
$("#ski").hide();
$("input:checkbox").change(function() {
this.checked?$("#ski").show():$("#ski").hide();
});
});
$(document).ready
(
function()
{
$("#ship").hide();
$("input:checkbox").change(function() {
this.checked?$("#ship").show():$("#ship").hide();
});
});
$(document).ready
(
function()
{
$("#sun").hide();
$("input:checkbox").change(function(){
this.checked?$("#sun").show():$("#sun").hide();
});
});
Html:
<div>
<input type="checkbox"></input>
<label> Pumpkins </label>
<img src="images/pumpkins.jpg" id="pump">
<input type="checkbox"></input>
<label> Ski Resort </label>
<img src="images/ski resort.jpg" id="ski">
<input type="checkbox"></input>
<label> Bahamas </label>
<img src="images/bahamas.jpg" id="sun">
<input type="checkbox"></input>
<label> Cruise </label>
<img src="images/cruise.jpg" id="ship">
</div>

$(window).on("load", function() {
$("#pump").hide();
$("#ski").hide();
$("#sun").hide();
$("#ship").hide();
});
$("#id1").change(function() {
if(this.checked) {
$("#pump").show();
}
else{
$("#pump").hide();
}
});
$("#id2").change(function() {
if(this.checked) {
$("#ski").show();
}
else{
$("#ski").hide();
}
});
$("#id3").change(function() {
if(this.checked) {
$("#sun").show();
}
else{
$("#sun").hide();
}
});
$("#id4").change(function() {
if(this.checked) {
$("#ship").show();
}
else{
$("#ship").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "id1" type="checkbox"></input>
<label> Pumpkins </label>
<img src="images/pumpkins.jpg" id="pump">
<input id = "id2" type="checkbox"></input>
<label> Ski Resort </label>
<img src="images/ski resort.jpg" id="ski">
<input id = "id3" type="checkbox"></input>
<label> Bahamas </label>
<img src="images/bahamas.jpg" id="sun">
<input id = "id4" type="checkbox"></input>
<label> Cruise </label>
<img src="images/cruise.jpg" id="ship">
You need to create ids for your checkboxes.
And within your event listener for the checkbox, you have to check whether the box has been selected or not. I like tu use IF ELSE.

Related

Unclick radio button via label instead of the actual button

I know this has been asked a few times but I haven't seen any posts regarding the use of the labels. The code below works for deselecting a radio button when no labels are written.
How can I add labels which allow the radio buttons to be selected/deselected with the clicking of the words rather than just the radio button itself. When I add labels my code seems to go haywire.
This is the working snippet with spans instead of labels
document.getElementsByName('foo').forEach((radioBttn) => {
radioBttn.addEventListener('click', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
document.getElementsByName('bar').forEach((radioBttn) => {
radioBttn.addEventListener('click', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
<span class="foo">
<input type="radio" name="foo"> Foo</span>
<span class="bar">
<input type="radio" name="bar"> Bar</span>
<br>
<span class="foo">
<input type="radio" name="foo"> Foo</span>
<span class="bar">
<input type="radio" name="bar"> Bar</span>
<br>
<span class="foo">
<input type="radio" name="foo"> Foo</span>
<span class="bar">
<input type="radio" name="bar"> Bar</span>
This is the non-working snippet with labels instead of spans
document.getElementsByName('foo').forEach((radioBttn) => {
radioBttn.addEventListener('mousedown', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
document.getElementsByName('bar').forEach((radioBttn) => {
radioBttn.addEventListener('mousedown', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
<label class="foo" for="foo1">
<input type="radio" name="foo" id="foo1">Foo</label>
<label class="bar" for="bar1">
<input type="radio" name="bar" id="bar1">Bar</label>
<br>
<label class="foo" for="foo2">
<input type="radio" name="foo" id="foo2">Foo</label>
<label class="bar" for="bar2">
<input type="radio" name="bar" id="bar2">Bar</label>
<br>
<label class="foo" for="foo3">
<input type="radio" name="foo" id="foo3">Foo</label>
<label class="bar" for="bar3">
<input type="radio" name="bar" id="bar3">Bar</label>

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>

Reveal div based on checked radio/checkbox, multiple instances

I have to add the class 'revealed' to a div, once the radio button with the label 'yes' has been selected. So far I have my code set up so that I apply a 'required' class to the input that will be revealed, but I need to have a way to add the class 'revealed' to the 'reveal-if-active' div. This entire HTML structure will repeat as there will be multiple yes/no questions after this first one. So each 'reveal-if-active' div must be unique.
Here's the HTML structure that I am required to use:
<div class="form-group two-column">
<input id="a1" type="radio" name="ayesno" value="1">
<label for="a1">yes</label>
</div>
<div class="form-group two-column">
<input id="a2" type="radio" name="ayesno" value="2">
<label for="a2">no</label>
</div>
<div class="reveal-if-active">
<label for="how-many-people">If <strong>yes</strong> how many people?</label>
<input type="text" name="a-how-many-people" class="require-if-active" data-require-pair="#a1" required="">
</div>
Here's the JS I have so far:
var FormStuff = {
init: function() {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function() {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function() {
$(".require-if-active").each(function() {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
$('[data-id=' + $('input:checked').prop('id') + ']').addClass('reveal');
} else {
el.prop("required", false);
el.removeClass("revealed");
}
});
}
};
FormStuff.init();
You may use el.closest('div.reveal-if-active'):
var FormStuff = {
init: function () {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function () {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function () {
$(".require-if-active").each(function () {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
el.closest('div.reveal-if-active').addClass("revealed");
} else {
el.prop("required", false);
el.closest('div.reveal-if-active').removeClass("revealed");
}
});
}
};
$(function () {
FormStuff.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group two-column">
<input id="a1" type="radio" name="ayesno" value="1">
<label for="a1">yes</label>
</div>
<div class="form-group two-column">
<input id="a2" type="radio" name="ayesno" value="2">
<label for="a2">no</label>
</div>
<div class="reveal-if-active">
<label for="i1">If <strong>yes</strong> how many people?</label>
<input id="i1" type="text" name="a-how-many-people" class="require-if-active" data-require-pair="#a1" required="">
</div>

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