I'm trying to create a button-with-a-checkbox by creating a span containing some text and a checkbox input.
The interaction I want is that whenever the 'button' or the checkbox is clicked, the state of the checkbox toggles.
However, I am suffering from the bubble-up problem, and I can't figure out how to fix it as all solutions on here seem to be JQuery solutions - I'm looking to do this is raw JS.
What I have so far is:
HTML:
<span id="myCBbutton" class="CBbutton" onClick="toggleIt(event);">Toggle Me <input type="checkbox" id="myCheckBox" onClick="toggleIt(event);event.stopPropagation();"></span>
CSS:
.CBbutton {
border: solid 1px black;
border-radius: 3px;
background-color: silver;
padding: 2px;
cursor: pointer;
}
and JS:
function toggleIt(event) {
var checkBox = document.getElementById('myCheckBox');
if (checkBox.checked) {
alert("before: it's checked!");
} else {
alert("before: NOT checked");
}
checkBox.checked = (checkBox.checked)?false:true;
if (checkBox.checked) {
alert("after: it's checked!");
} else {
alert("after: NOT checked");
}
event.stopPropagation();
return false;
}
I've also created a fiddle here.
I guess fromother questions and answers that the solution is something to do with either event.preventDefault() or event.stopPropagation() with or without a return false but I just can't get this to work.
To achieve what you want you can use an label instead of going to Javascript:
.CBbutton {
border: solid 1px black;
border-radius: 3px;
background-color: silver;
padding: 2px;
cursor: pointer;
}
Label with checkbox inside:<br>
<label id="myCBbutton" class="CBbutton">Toggle Me <input type="checkbox" id="myCheckBox"></label>
<br><br>
Label with checkbox outside<br>
<label class="CBbutton" for="myCheckBox2">Toggle Me</label>
<input type="checkbox" id="myCheckBox2">
But replying to your question, stopPropagation is what would make an event do not propagate to parent's handlers.
event.stopPropagation() is the good code, but your problem is elsewhere.
When you do this : checkBox.checked = (checkBox.checked)?false:true;, the browser fire a new click event and this one is bubbling to the parent.
But anyway, Luizgrs solution is the better i think.
You can use event.stopImmediatePropagation()
Sample Here
Documentation Here
My suggestion is that you use a label as suggested by Luizgrs
However, the problem with your code is that even though you are preventing propagation (the handler on the span is not called when you click the checkbox), the click on checkbox is going to change its checked status and your code is then switching it back. There are ways to fix it but it's not worth it, a <label> does the hard work for you
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.
This issue exists only in google chrome. If I have a checkbox with label inside a container which is having some focus styles. When I click on the label, I'm preventing moving the focus to container using e.preventDefault() but this is introducing one more issue. If we double click anywhere on the document OR select any text by mouse drag, then clicking on the label doesn't select the checkbox. But clicking on the checkbox directly does work fine.
If I clear the text using window.getSelection().removeAllRanges() it's working but doesn't allow the user to select the text of the label anymore.
Is this a bug with the chrome browser. I dont see any in the chromium bug forum.
Please check the code below..
document.getElementById('chkLabel1').onmousedown = function(e) {
e.preventDefault();
};
.container {
height: 300px;
width: 300px;
border: 3px solid black;
padding: 20px;
}
.container:focus {
border-color: red;
}
#chkLabel1:focus {
border: 1px solid red;
}
<div class="container" tabindex="0">
<input type="checkbox" id="chk1" />
<label id='chkLabel1' for="chk1"> with preventDefault </label>
<br/>
<input type="checkbox" id="chk2" />
<label for="chk2"> without preventDefault </label>
</div>
Here is the fiddle link
https://jsfiddle.net/zgz2j8ad/
A better solution would seem to be this:
document.getElementById('chkLabel1').onfocus = function(e) {
e.preventDefault();
};
This will only stop it being focused.
I wrote a script to check checkbox when I am clicking on it's respective image.
Image have id like checkbox-img-1 and checkbox input have id like checkbox-1 for 1st pair of checkbox and image. For 2nd pair id's are checkbox-img-2 and checkbox-2 and so on.
So, whenever I click on image I want to check the respective checkbox. For few images the UI is getting updated but for few images it's not getting updated.
What is the possible problem? I searched a bit but all questions were doing mistake of having attr in place of prop.
My script is in pure javascript. I tried with jQuery but I am getting same bug.
I figured out that content which is not present or not yet displayed in front are not getting selected.
The javascript code is:
/* Check option on image click */
$(".option-check-img").click(function () {
var checkbox_img_id = $(this).attr("id");
var checkbox_id = checkbox_img_id.replace("checkbox-img", "checkbox");
if(document.getElementById(checkbox_id).checked)
{
document.getElementById(checkbox_id).checked = false;
var d = document.getElementById(checkbox_img_id);
d.className = "img-circle pointer";
/*$("#checkbox_id").prop("checked", false);
$("#checkbox_img_id").removeClass("img-border");
console.log(document.getElementById(checkbox_id));*/
}
else
{
document.getElementById(checkbox_id).checked = true;
var d = document.getElementById(checkbox_img_id);
d.className += " img-border";
/*$("#checkbox_id").prop("checked", true);
$("#checkbox_img_id").addClass("img-border");
console.log(document.getElementById(checkbox_id));*/
}
});
Any solution? Thank you.
Try to use prop() instead of attr()
JQuery Script not checking check-boxes correctly
Read docs for more info jQuery prop().
Are you sure you want to use js for this? You can do this just with css.
*, *:before, *:after {
font-family: sans-serif;
box-sizing: border-box;
}
label {
display: block;
margin-bottom: 20px;
cursor: pointer;
}
span:before {
content: '';
display: inline-block;
width: 15px;
height: 15px;
margin-right: 10px;
background: white; /* you can place your image url here */
border: 4px solid white;
border-radius: 3px;
box-shadow: 0 0 0 1px black;
}
input {
display: none;
}
input:checked + span:before {
background: black;
}
<label>
<input type="checkbox">
<span>Checkbox 1</span>
</label>
<label>
<input type="checkbox">
<span>Checkbox 2</span>
</label>
There is a pure-html solution (Fiddle):
<ul><li>
<input type="checkbox" id="checkbox-1" />
<label for="checkbox-1"><img /></label>
</li>
<li>
<input type="checkbox" id="checkbox-2" />
<label for="checkbox-2"><img /></label>
</li></ul>
if you need to add styling to your images when checkbox is checked you can use css3 (Fiddle):
input:checked + label img{
border: 1px solid black;
}
input:not(:checked) + label img{
border: 1px solid green;
}
// If you want to hide the checkbox
input[type=checkbox] {
display: none;
}
You should build your html such the checkbox and the image are next to each other.
This approach is much more elegant and doesn't use unnecessary javascript.
$(".option-check-img").click(function() {
var $this = $(this);
var checkbox_img_id = $(this).attr("id");
var checkbox_id = checkbox_img_id.replace("checkbox-img", "checkbox");
if ($("#" + checkbox_id + ":checked").length) {
$("#" + checkbox_id).prop('checked', false);
$("#" + checkbox_img_id).removeClass("img-border");
$("#" + checkbox_img_id).addClass("img-circle pointer");
} else {
$("#" + checkbox_id).prop('checked', true);
$("#" + checkbox_img_id).removeClass("img-circle pointer");
$("#" + checkbox_img_id).addClass("img-border");
}
});
Converted your code to proper jQuery Code.
Assumption: ID is of your check-box element.
Make sure no elements have same ID in your DOM.
Updated code to remove alternate-classes too.
Thanks
your checkbox id's are not unique.
A different checkbox with the same id is getting checked / unchecked instead of the one you want to manupulate. getElementById / $('#id') will return only one element which ever it finds first.
for instance, in the link that you shared the option Party has a id of checkbox-24 but with the same id there are total of three checkboxes.
similarly for Music with a id of checkbox-27 there are again 3 instances of checkbox with that id.
Your script is correct, but the ids are not unique. Make the id's unique or use someother identifier or combination of identifiers to uniquely identify the checkbox which you want to manipulate.
the problem was with infinite loop. Without infinite loop its working. But still I want that infinite slider so I will try something different.
I have div (.upload-drop-zone, yellow zone at screenshot) with another div (.dropzone-width, blue zone) inside.
<div class="upload-drop-zone dz-clickable" id="drop-zone-600">
<div class="dropzone-width">600 PX</div>
</div>
There is a javascript onclick event attached to .upload-drop-zone (when I click on it, it shows file chooser dialog). Event attached by third-party plugin, so I have no access to function which be called.
The problem is that if I make click on .dropzone-width, click event did not pass to .upload-drop-zone so nothing happens instead of showing file chooser dialog. What can I do to fix it?
P.S.: Sorry for bad english.
Try this, I had a same issue before. No javscript required...
.dropzone-width { pointer-events: none; }
You can listen for a click in the inner div and fire the click on the outer div.
$("#drop-zone-600").click(function (e) {
alert("hey");
});
$("#dzw").click(function (e) {
$("#drop-zone-600").onclick();
});
.upload-drop-zone {
width: 200px;
height: 200px;
border: 1px solid red;
background: darkred;
}
.dropzone-width {
width: 100px;
height: 100px;
border: 1px solid green;
background: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upload-drop-zone dz-clickable" id="drop-zone-600">
<div id ="dzw" class="dropzone-width">600 PX</div>
</div>
Despite the fact that the alert function is inside the click event listener of the #drop-zone-600 div, you can see the alert by clicking any of the divs.
One possibility is to synthetically fire the click event. See How can I trigger a JavaScript event click
fireEvent( document.getElementById('drop-zone-600'), 'click' );
Try this via jquery:
$(".dropzone-width").on("click", function(){
$("#drop-zone-600").trigger("click");
});