Suppose, we have 2 checkboxes and 2 divs that follow the checkboxes:
<div class="wrapper">
<input type="checkbox" name="checkbox1" checked="" />
</div>
<div class="border"></div>
<div class="wrapper">
<input type="checkbox" name="checkbox2" checked="" />
</div>
<div class="border"></div>
My goal is to toggle the color of the appropriate "border" div, lying below the checkbox. The problem is, I don't know how to get the appropriate div. I tried this, but it doesn't work:
$('input[type="checkbox"]').change(
function ()
{
var div = $(this).find('div');//<-- ?
if ($(this).checked)
{
div.css("border", "solid 2px blue");
}
else
{
div.css("border", "solid 2px black");
}
});
jsfiddle
The problem is that the .find() method will select any descendant elements.
Since the input element is self-closed and doesn't contain any descendant elements, nothing is selected with $(this).find('div').
You could select the parent div element, and then the immediately following element:
$(this).parent().next();
The above will select the immediate parent element. It may be safer using the .closest() method in order to select the ancestor .wrapper element (just in case nesting varies):
$(this).closest('.wrapper').next();
In addition, jQuery objects don't have a checked property, you should retrieve the checked property of the DOM element, therefore $(this).checked should be this.checked or you could simply use the .prop() method to retrieve the checked property from the DOM element in the jQuery object by using: $(this).prop('checked').
Updated Example
$('input[type="checkbox"]').on('change', function() {
var div = $(this).closest('.wrapper').next();
if (this.checked) {
div.css("border", "solid 2px blue");
} else {
div.css("border", "solid 2px black");
}
});
As a side note, I'd suggest simply toggling a class on the corresponding element instead:
Updated Example
.border.blue-border {
border-color: blue;
}
$('input[type="checkbox"]').on('change', function() {
$(this).closest('.wrapper').next().toggleClass('blue-border')
});
Change it to var div = $(this).parent().next('.border');
You need to take parent().next() as was mentioned in some answers...
Also, checkbox status was not valuated correctly.
Try this solution:
$('input[type="checkbox"]').change(
function () {
var div = $(this).parent().next();
if ($(this).is(":checked")) {
div.css("border", "solid 2px blue");
} else {
div.css("border", "solid 2px black");
}
}
);
https://jsfiddle.net/gv3pqo2z/3/
Related
I'm clicking on a checkbox to add some animation to a div, but when I want this animation to disappear I can only make it happen through $(document) click. Checkbox must add and then remove the class.
JS
$('#inOrder').click(function(e) {
$('.border').addClass('colorsborder');
e.stopPropagation();
$(document).click(function(e) {
$('.border').removeClass('colorsborder');
});
});
$('#inOrder').click(function(e) {
e.stopPropagation();
});
HTML
<input id="inOrder" type="checkbox" />
You may call toggleClass() method on the jQuery object (element) that you want to add or remove the class from. The method toggleClass will either:
add the desired class when the element doesn't have it.
or remove that class when the element has it already.
Here's a basic, live demo to illustrate the functionality:
const checkbox = $('#inOrder'),
relatedDiv = $('#related');
checkbox.on('change', () => relatedDiv.toggleClass('custom'))
/** just for demo purpose */
#related {
margin: 15px 0;
padding: 10px;
border: 1px solid #ccc;
}
#related.custom {
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inOrder" type="checkbox" />
<div id="related">My appearnace will change on checkbox click</div>
The above demo is pnly meant as a showcase of a possible solution that could be applied to your current problem and it WON'T do the exact thing you want to have unless you apply the required changes you need to suit your actual code/structuring.
Then you want to toggle the class not add it when you click on checkbox
$('#inOrder').click(function(e) {
$('.border').toggleClass('colorsborder');
....
I'm currently building a form that has checkboxes wrapped inside of labels. We are doing this because we need to swap our the original checkbox for an image. However, when the checkbox is checked, we need to make the label have a border to give some user feedback.
Here is the setup of the labels/checkboxes
<div class="one_column">
<label for="fieldname2_1_cb0">
<input name="fieldname2_1[]" id="fieldname2_1_cb0" class="field depItem group required" value="Alloy Wheel(s)" vt="Alloy Wheel(s)" type="checkbox"> <span>Alloy Wheel(s)</span>
</label>
</div>
We have tried going about is using the following but obviously doesn't work
label input[type="checkbox"]:checked + label {
border: 5px solid blue;
}
Any help would be appreciated!
I have managed to the the first checkbox using the code supplied below
window.onload=function() {
document.querySelector('input[type="checkbox"]').addEventListener('change',
function() {
if (this.checked) {
this.parentNode.classList.add('border-blue');
} else {
this.parentNode.classList.remove('border-blue');
}
})}
However, it only changes the first checkbox... there are 10 in total all following the same structure as above
Using CSS, there is no way to select parent elements from child elements.
If you are allowed to use JavaScript, you can solve it this way:
document.querySelectorAll('input[type="checkbox"]').forEach(function(el) {
el.addEventListener('change', function() {
if (this.checked) {
this.parentNode.classList.add('border-blue');
} else {
this.parentNode.classList.remove('border-blue');
}
})
})
.border-blue {
border: 5px solid blue;
}
It will check for changes on input. If it is checked, a class will be added. Otherwise, the class will be removed.
I am just working on my new webspace and I have a small problem.
I know have to input tags with an onclick function
<script>
function mark( el ) {
el.style.borderBottom= "3px solid white";
}
</script>
When I click on the first input the border appears as I want but when I click on the other input the border of the first input tag is still there.
So how can I let the function only work when it's only clicked on the input tag itself and not when another input is clicked as well
Thanking you in anticipation
Just use CSS's :focus pseudo class:
input:focus {
border-bottom:3px solid red;
}
<input type="text">
<input type="text">
MDN Docs
You can easily use CSS Focus selector. input:focus
input:focus {
background-color: yellow;
border-bottom:3px solid white;
}
<div><input type="text"></div>
<br/>
<div><input type="text"></div>
Before you add style to this specific element you can remove style of all inputs or something like this:
function mark( el ) {
var input = document.getElementsByTagName("input");
for(var i =0;input.length>i;i++){
input[i].removeAttribute("style");
}
el.style.borderBottom= "3px solid white";
}
Here is what I would do. First, create a mark and an unmark functions. Then trigger the mark function at "onmousedown" and unmark at "onmouseup" event. Therefore, this border will only be shown when you have the mouse button pressed.
<script>
function mark( el ) {
el.style.borderBottom= "3px solid white";
}
function unmark( el ) {
el.style.borderBottom= "none";
}
</script>
Sample:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Toggle</title>
<style>
#first {
color: blue;
}
#second {
border: 1px solid green;
}
#third {
background: tan;
}
</style>
</head>
<body>
<label for="box">Toggle</label>
<input type="checkbox" id="box" onchange="toggle();">
<div id="first">First</div>
<div id="second">Second</div>
<div id="third">Third</div>
<script>
function toggle() {
var box = document.getElementById('box');
var first = document.getElementById('first');
var second = document.getElementById('second');
var third = document.getElementById('third');
if (box.checked) {
first.style.color = 'red';
second.style.border = '2px dotted blue';
third.style.background = 'olive';
} else {
first.style.color = 'blue';
second.style.border = '1px solid green';
third.style.background = 'tan';
}
}
</script>
</body>
</html>
DEMO
I wonder if an input checkbox is the right element to create a toggle. I also want to know how to undo what I have in the if clause: in else do I have to repeat my stylesheet or is there a shorter neater way to get back to the initial state?
You can do it in better way like this: demo
Add a parent div in html like this:
<div id="parent">
<div id="first">First</div>
<div id="second">Second</div>
<div id="third">Third</div>
</div>
Then handle your front end with css instead inline styling:
.checked #first {
color:red;
}
.checked #second {
border:2px dotted blue;
}
.checked #third {
background:olive;
}
Then add and remove only one class with javascript:
function toggle() {
var box = document.getElementById('box');
var parent = document.getElementById('parent');
if (box.checked) {
parent.className = parent.className + "checked";
} else {
parent.className = "";
}
}
1. I wonder if an input checkbox is the right element to create a toggle?
Definition of toggle*:
COMPUTING a key or command that is operated the same way but with
opposite effect on successive occasions.
Explanation of checkbox**:
In computing, a checkbox (check box, tickbox, or tick box) is a
graphical user interface element (widget) that permits the user to
make a binary choice, i.e. a choice between one of two possible
mutually exclusive options.
So yes, it is the best choice.
2. I also want to know how to undo what I have in the if clause: in else do I have to repeat my stylesheet or is there a shorter neater way to get back to the initial state?
In order to do this you could using jQuery:
Use either addClass()/removeCLass() methods or toggleClass(); You would put your active class stylings into a new class, apply these then simply remove them on the else/off state. This would also mean you maintain the separation between contents and styling.
Or regular JS:
.setAttribute("class", "active"); and .removeAttribute("class", "active"); or simply .removeAttribute("style"); to unset the styles you applied inline and revert to the original state.
*Source
**Source
To answer the second question:
You could use getElementById("id").removeAttribute("style"); to remove inline styles.
if (box.checked) {
first.style.color = 'red';
second.style.border = '2px dotted blue';
third.style.background = 'olive';
} else {
first.removeAttribute("style")
second.removeAttribute("style")
third.removeAttribute("style")
}
The question of how to detect a click on anywhere except a specified element has been answered a couple of items like here:
Event on a click everywhere on the page outside of the specific div
The problem I have is trying to figure out how to detect a click anywhere except a given element including one of it's children.
For example in this code:
http://jsfiddle.net/K5cEm/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(function() {
$(document).click(function(e) {
$('#somediv').hide();
});
$('#somediv').click(function(e) {
e.stopPropagation();
});
});
</script>
<div style="border: 1px solid red; width:100px; height: 100px" id="somediv">
<span style="display: block; border: 1px solid green; width:50px; height: 50px; margin: 0 auto" id="someSpan"></span>
</div>
Clicking anywhere outside the red div should cause it to hide. Not only that but also clicking on it's child element (the green span) should cause it to hide. The only time it shouldn't hide is if you click on it but not on the span. As it stands now, the click on the span is also considered a click on the parent div hence it doesn't hide the div if the span is clicked.
How to achieve this?
You can compare the click's target to the element in question:
$(document).click(function(e) {
if (e.target != $('#somediv')[0]) {
$('#somediv').hide();
}
});
Demo: http://jsfiddle.net/K5cEm/7/
Add this:
$('#somediv').click(function(e) {
e.stopPropagation();
}).children().click(function(e) {
$('#somediv').hide();
});
Here's your updated working fiddle: http://jsfiddle.net/K5cEm/5/
I'd do it like so:
$(function () {
var elem = $( '#somediv' )[0];
$( document ).click( function ( e ) {
if ( e.target !== elem ) {
$( elem ).hide();
}
});
});
Live demo: http://jsfiddle.net/uMLrC/
So this
var elem = $( '#somediv' )[0];
caches the reference to the DIV element. We want to cache this reference on page load, so that we don't have to query for that element repeatedly. And it improves the readability of the code, also.