Wrapping Checkbox on Checked with .is() not working - javascript

I have the following code snippet. Why might the .is() not be working on wrapping only the checked checkboxes?
$("input:checkbox").on("change", function() {
$("input:checkbox").is(":checked").wrap("<span class='check-wrap-sapn'></div>");
});
.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">

.is() returns a boolean so it is not chainable. You want .has()
Now the issue you have is if the user unchecks it, it still will be wrapped and if they check it again, you will have multiple wrapped elements. You probably should just wrap the element to start and toggle the class on the parent element.
$("input:checkbox").on("change", function() {
$(this).closest("label").toggleClass("checked", this.checked);
}).trigger("change");
label.checked {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox">
</label>
<label>
<input type="checkbox">
</label>
<label>
<input type="checkbox">
</label>

Read the documentation of .is:
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
So the return value of .is is a boolean. But you're trying to call a jQuery method on it.
Additionally, you're repeating your DOM query within the event handler, and so will act on all matching elements, not just the one that relates to the event.
And your wrapper starts out as a div but ends as a span. Might want to be consistent about that.
And I suspect check-wrap-sapn was meant to be check-wrap-span.
If I'm guessing correctly at your goal, then:
$("input:checkbox").on("change", function() {
var $this = $(this);
if ($this.is(":checked")) {
$this.wrap("<span class='check-wrap-span'></span>");
} else {
$this.unwrap();
}
});
Or:
$("input:checkbox").on("change", function() {
if (this.checked) {
$(this).wrap("<span class='check-wrap-span'></span>");
} else {
$(this).unwrap();
}
});
Live Example:
$("input:checkbox").on("change", function() {
if (this.checked) {
$(this).wrap("<span class='check-wrap-span'></span>");
} else {
$(this).unwrap();
}
});
.check-wrap-span {
border: 1px solid green;
}
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
But this is something that would be much better handled with styling the CSS, via the :checked pseudo-class, provided the styling in question can be applied to checkboxes. If it can't, I'd advocate always having the wrapper span, but toggling a class on it:
Live Example:
$("input:checkbox").on("change", function() {
$(this.parentNode).toggleClass("check-wrap-span", this.checked);
});
.check-wrap-span {
border: 1px solid green;
}
<span><input type="checkbox"></span>
<span><input type="checkbox"></span>
<span><input type="checkbox"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Use $(this) inside the event handler to check if the checkbox is checked
is returns boolean result, use is() in if and if the checkbox is checked, then wrap it.
$("input:checkbox").on("change", function() {
var $this = $(this);
if ($this.is(":checked"))
$this.wrap("<span class='red'></div>");
});
.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">

Related

Changing a class outside an input element

I have an input element with a checkbox:
<input type="checkbox" id="ID1" name="ID1" checked>
Somwhere else (outside the input field), I would like to have a text, which is changing its appearence according the check status of the input element with the ID1.
Something like:
<span for id='ID1' class='Class1'>TEST</span>
How do I get a dependency between the text and the status of the input field and how is it possible to change Class1 to Class2 by checking and unchecking the checkbox? The class changes the background color of the Text. I know how to do this inside the same element. But having two different elements? Or is it possible to access the class via the ID of the input element, due to the "for" statement? I am working with javascript.
Thanks for any help!
Add an attribute to the checkbox with the ID of the related span.
document.querySelector("#ID1").addEventListener("click", function() {
let rel = document.getElementById(this.getAttribute("rel"));
if (rel) {
if (this.checked) {
rel.classList.add("Class1");
rel.classList.remove("Class2");
} else {
rel.classList.add("Class2");
rel.classList.remove("Class1");
}
}
});
.Class1 {
background-color: red;
}
.Class2 {
background-color: blue;
}
<input type="checkbox" id="ID1" name="ID1" checked rel="span1">
<span id="span1" class='Class1'>TEST</span>
First : you can't/shouldn't have two element with same Id
const checkbox = document.getElementById("ID1");
const span = document.getElementById("SpanID1");
checkbox.addEventListener('change', function() {
if (this.checked) {
span.innerHtml= 'TEST Checked'
} else {
span.innerHtml= 'TEST Unchecked'
}
});
If you want a CSS solution, you can target the input box and use the :checked selector followed by + then the adjacent element.
CSS: element+element [div + p] Selects the first <p> element that is placed immediately after <div> elements
.Class1 {
background-color: yellow
}
#ID1:checked + .Class1 {
background-color: skyblue
}
<input type="checkbox" id="ID1" name="ID1" checked>
<span for id='ID1' class='Class1'>TEST</span>
Check here to know more about the different CSS selectors.

Click event affects only the first element jquery [duplicate]

This question already has answers here:
jQuery click function only works on first element
(8 answers)
Closed 3 years ago.
I am writing an application where the user selects by toggling the switch button but the click event affects only the first element.
<label class="switch">
<input type="checkbox" id="block-instructors" class="block-instructors" value="FMmRXgApuo5AZe4zGqUl">
<span class="slider round"></span>
</label>
<label class="switch">
<input type="checkbox" id="block-instructors" class="block-instructors" value="J0jcK7eUvadzSNaaoG2h">
<span class="slider round"></span>
</label>
$("#block-instructors").on('change', function(e){
if ($(this).is(':checked')) {
$(this).attr('value');
alert($(this).val());
}
else {
$(this).attr('value', 'false');
alert($(this).val());
}
});
You can't have the same id for two elements on one page. Use this instead
$(".block-instructors").on('change', function(e) {
if ($(this).is(':checked')) {
$(this).attr('value');
alert($(this).val());
} else {
$(this).attr('value', 'false');
alert($(this).val());
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="switch">
<input type="checkbox" id="block-instructors" class="block-instructors" value="FMmRXgApuo5AZe4zGqUl">
<span class="slider round"></span>
</label>
<label class="switch">
<input type="checkbox" id="block-instructors" class="block-instructors" value="J0jcK7eUvadzSNaaoG2h">
<span class="slider round"></span>
</label>
Use class instead of id:
$(".block-instructors").on('change', function(e){
You should have the unique id for individual element or tag. When you are clicking it is referring to last one since the code executes line by line. Try this code instead.
$("#block-instructors1").on('change', function(e,value){
if ($(this).is(':checked')) {
$(this).attr('value');
alert($(this).val());
}
else {
$(this).attr('value', 'false');
alert($(this).val());
}
});
$("#block-instructors2").on('change', function(e,value){
if ($(this).is(':checked')) {
$(this).attr('value');
alert($(this).val());
}
else {
$(this).attr('value', 'false');
alert($(this).val());
}
});
To select the first element or any of the first nth element in jquery can be done easily by :nth-child() selector in jquery
For example for 2nd li in ul:
$("ul li:nth-child(2)")
Reference can be found here
Here you have defined multiple tags with same Id. Your jQuery function starts searching for the Id 'block-instructors' and returns you where it finds first in DOM. You must convert block-instructors from Id to class and then access it

On input type=radio checked, add a class to input=text

How can I link a radio button and a text input filled so when the radio is selected the text in the input text area will also change to lets say... red-bold?
I know the logic is:
When radio-A and input-text-A is checked, add CSS class to input-text-A.
When unchecked remove class. If radio-B is selected change input-text-B, and so on...
But right now the simple script targets all text inputs.
$('input[type=text]').addClass('red');
.red {
color: red;
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-inline">
<label class="" for="">
<input class="" type="radio" name="answer-Q1" value="option1"> A. </label>
<input type="text" name="answers" class="" placeholder="" required>
</div>
<br>
<div class="form-inline">
<label class="">
<input class="" type="radio" name="answer-Q2" value="option1"> B. </label>
<input type="text" name="answers" class="" placeholder="" required>
</div>
Give your markup, there's actually no need to add any classes or use javascript, you can do what you want with pure CSS:
input[type="radio"]:checked + input[type="text"] {
color: red;
font-weight: bold;
}
As for how to add the class with jQuery, I tend to write "robust" solutions that are maybe a bit longer, but are not as "brittle" (meaning: if markup changes a bit, the script will still work). The way I would write this - assuming no control over markup - would be using jQuery's closest and find to locate the target text inputs:
// no-conflict-save document ready shorthand
jQuery(function($) {
// bind to the "change" event of all inputs that are radio buttons
jQuery('input[type="radio"]').on('change', function() {
// find the text input
var $text_input = $(this).closest('div').find('input[type="text"]');
// if there isn't one, get out
if ( ! $text_input.length ) {
return;
}
// if the radio button is checked, add the class
if ($(this).is(':checked')) {
$text_input.addClass('red');
} else {
// otherwise, remove the class
$text_input.removeClass('red');
}
});
});
However, if I DID have control over markup, I would add a class to the radio input element, and use that to both make the script more "generically" useful, as well as narrow down the scope of which inputs were being bound (which would allow this same script to work effectively on checkboxes + text inputs as well):
// no-conflict-save document ready shorthand
jQuery(function($) {
// bind to the "change" event of any inputs with the "watch-change" class
jQuery('input.watch-change]').on('change', function() {
// find the text input. Note, this would find multiple text inputs if they existed.
var $text_input = $(this).closest('div').find('input[type="text"]');
// if there isn't a text input to work with, get out
if ( ! $text_input.length ) {
return;
}
// if the radio button is checked, add the class
if ($(this).is(':checked')) {
$text_input.addClass('red');
} else {
// otherwise, remove the class
$text_input.removeClass('red');
}
});
});
And, honestly, with a better understanding of your project scope, it might be possible to write an even more efficient, re-usable snippet of script.
Do this:
$("input[type=radio]").on("change", function(e) {
if (e.currentTarget) {
e.currentTarget.next("input[type=text").addClass("red");
}
});
Here is the working code.
$('input:radio').click(function() {
$('label:has(input:radio:checked)').addClass('rightAnswer');
$('label:has(input:radio:not(:checked))').removeClass('rightAnswer');
});
.container {margin:0 auto; margin-top:50px;}
.rightAnswer {font-weight:bold; color:#2979FF;}
.inputAnswers {width:200px;}
.block {display:block;}
input[type="radio"]:checked + input[type="text"] {
color: #2979FF;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<label class="block" for="answer-Q1A">
<input type="radio" class="" name="answer-Q1" value="1"> A.
<input type="text" name="answers" class="inputAnswers" id="answer-Q1A" placeholder="" required></label>
<label class="block" for="answer-Q1A">
<input type="radio" class="" name="answer-Q1" value="1"> B.
<input type="text" name="answers" class="inputAnswers" id="answer-Q1A" placeholder="" required></label>
<label class="block" for="answer-Q1A">
<input type="radio" class="" name="answer-Q1" value="1"> C.
<input type="text" name="answers" class="inputAnswers" id="answer-Q2A" placeholder="" required></label>
</div>

Why is toggleClass not working here?

I'm trying to add / remove a class on click here, but toggleClass is not working as I'm expecting it to. On the contrary, addClass works fine, but I need it to remove the class on the second click.
$('.label1').on('click', function() {
var $checkItem = $(this).find('input[type=checkbox]');
$(this).toggleClass('checked');
$checkItem.prop("checked", !$checkItem.prop("checked"));
})
$('.label2').on('click', function() {
var $checkItem = $(this).find('input[type=checkbox]');
$(this).addClass('checked');
$checkItem.prop("checked", !$checkItem.prop("checked"));
})
Can you tell me what am I doing wrong?
See it in action here: Test jquery.
Thanks!
You can avoid the problem and simplify your logic by instead hooking to the change event of the checkbox. This then lets you set the checked class on the parent label based on the state of the checked property.
Using change over click on the checkbox is also much better for meeting accessibility standards as it allows users who navigate using the keyboard to trigger the same effects in the UI. Try this:
$(':checkbox').on('change', function() {
$(this).closest('label').toggleClass('checked', this.checked)
});
.checked {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="checkbox">
<label class="label1">
<input type="checkbox">
Check me out
</label>
</div>
<div class="checkbox">
<label class="label2">
<input type="checkbox">
Check me out
</label>
</div>
</form>
Here you can do it like this.
Try this example hope it will helps you.
$('.label1').on('click', function() {
var $checkItem = $(this).find('input[type=checkbox]');
$(this).toggleClass('checked');
if($(this).hasClass('checked')) {
$checkItem.prop("checked", true);
} else {
$checkItem.prop("checked", false);
}
})
$('.label2').on('click', function() {
var $checkItem = $(this).find('input[type=checkbox]');
if($(this).hasClass('checked')) {
$checkItem.prop("checked", false);
$(this).removeClass('checked');
} else {
$(this).addClass('checked');
$checkItem.prop("checked", true);
}
})
.checked {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="checkbox">
<label class="label1">
<input type="checkbox">
Check me out
</label>
</div>
<div class="checkbox">
<label class="label2">
<input type="checkbox">
Check me out
</label>
</div>
</form>
The checkbox is inside you label so when it gets clicked it is clicking the checkbox too.
$('.label1, .label2').on('change', function() {
$(this).toggleClass('checked');
})
https://codepen.io/ankurace/pen/OgoQLG
This is a compact solution
$('input[type=checkbox].BorderRed').change(function() {
$($(this).parent()).toggleClass('checked');
});
NEW checkbox Object,
if you wont the effect
<div class="checkbox">
<label class="label2">
<input class="BorderRed" type="checkbox">
Check me out
</label>
</div>
if you dont wont the effect
<div class="checkbox">
<label class="label2">
<input type="checkbox">
Check me out
</label>
</div>

How to show a div box when user firstly checked a checkbox out of some checkboxes it may be 7 or more and hide on last uncheck of any checkbox?

I want to get appear a div box when user checks any first checkbox.
I have also tried following codes:
JQ Codes:
$('#checkbox').change(function() {
if ($(this:first).is(':checked')) {
console.log('Checked');
} else {
console.log('Unchecked');
}
});
HTML Codes:
<?php foreach ($band_data as $row) { ?>
<fieldset>
<legend>Text</legend>
<input type="checkbox" class="scheme-check" id="checkscheme" name="checkme">
</fieldset>
<?php } ?>
<!--Div to be shown on hide-->
<div class=counter-box></div>
But not working please tell me any correct method to do so.
First of all thanks for instant help; I should mention the case properly to avoid misunderstanding. I use those new codes but due to 'toggle' event its hiding when I checked/unchecked any checkbox. I want to show box till last checkbox is checked and will be hide it on last uncheck.
Take a look at this: http://jsfiddle.net/nq65qnr0/
JavaScript:
// Bind the change event to the common class of all the checkboxes.
$('.scheme-check').change(function(){
if($(".scheme-check:checked").length>1) return; // If not the first one, then do nothing.
if($(this).is(':checked')) {
console.log('Checked');
//show hide div here
}
else {
console.log('Unchecked');
}
});
Assuming your HTML generated to be like this:
<input type="checkbox" class="scheme-check" id="checkscheme1" name="checkme">
<input type="checkbox" class="scheme-check" id="checkscheme2" name="checkme">
<input type="checkbox" class="scheme-check" id="checkscheme3" name="checkme">
.....
(HTML)
<input class="check-box" type="checkbox">Check Me</input>
<input class="check-box" type="checkbox">Check Me</input>
<input class="check-box" type="checkbox">Check Me</input>
<input class="check-box" type="checkbox">Check Me</input>
<div class="hidden"></div>
(CSS)
.hidden {
display: none;
height: 100px;
width: 100px;
background-color: blue;
}
(JavaScript)
$(document).ready(function() {
checkBox();
});
function checkBox() {
$('.check-box').on("change", function() {
$('.hidden').toggle();
});
}
Whatever you are doing is correct but use class instead of id
$('.scheme-check').change(function() {
if ($(this).is(':checked')) {
console.log('Checked');
} else {
console.log('Unchecked');
}
});

Categories