How to attach click event to a css styled checkbox - javascript

Having a hard time attaching a click event. I just want to do a few calculations when user checks a checkbox.
When a checkbox is checked the span's class becomes 'checked' & 'unchecked' when unchecked.
The input checkbox is not displayed & also its attribute 'checked' is not applied, when checked, making it even more difficult.
HTML:
<div class="checkboxBtn" style="border:1px solid blue;">
<span class="cheked" style="width:20px;height:20px;border:1px solid red;"
onclick="CheckSelected();">
</span>
<input id="23" type="checkbox" style="border:1px solid green;"></input>
<label>Compare Now</label>
</div>
None of these worked:
JS:
$(document).ready(function () {
$(".cheked").click(function () {
alert(".cheked");
})
$(".uncheked").click(function () {
alert(".uncheked");
})
})
function CheckSelected() {
alert("");
return false;
}
Is this not working because, there might be already a click event to show the tick image.
If there is any already, how can I do my task, without disturbing the existing functionality.

Try this
- Apply class to Checkbox and bind change event.
<div class="checkboxBtn" style="border:1px solid blue;">
<span class="cheked" style="width:20px;height:20px;border:1px solid red;"
onclick="CheckSelected();">
</span>
<input id="23" class="chkBx" type="checkbox" style="border:1px solid green;"></input>
<label>Compare Now</label>
</div>
$(document).ready(function() {
$('.chkBx').change(function() {
if($(this).is(":checked")) {
$(this).closest('span').removeAttr('class');
$(this).closest('span').addClass('checked');
}
else{
$(this).closest('span').removeAttr('class');
$(this).closest('span').addClass('unchecked');
}
});
});

This is because the '.click' handler will attach event to all of the matched element specified by selector at the time of invocation but not to the future element. i.e if an element with class name 'cheked' added later by JavaScript, the click handler will not be attached to that obviously.
Therefore you should add a dummy static class to attach handler. Note that event attached to the checkedbox is fired after changing the checkbox status.

Here is the updated working code.
<div class="checkboxBtn">
<span id="23_span" class="unchecked"></span>
<input type="checkbox" id="23"></input>
<label for="23">Compare Now</label>
</div>
<script>
$(document).ready(function () {
$("#23").click(function () {
CheckSelected();
})
})
function CheckSelected() {
if(document.getElementById('23').checked) {
$("#23_span").removeClass("unchecked").addClass("checked");
alert("checked");
}
else {
$("#23_span").removeClass("checked").addClass("unchecked");
alert("unchecked");
}
}
</script>
Now you can provide CSS to your span element according to the requirement.

Related

How to click radio by clicking on div?

Why is my code not working? i need to simulate click on radio button. Radio button has click event.
$(".form-group").click(function() {
alert("clicked")
$(this).closest(".hotelObj", function() {
$(this).trigger("click");
})
});
.form-group {
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="male" style="font-weight:800;">chose
<input type="radio" value="z6" class="hotelObj" name="hotelType">
<p>description</p>
</label>
</div>
Given the markup you've provided, javascript isn't necessary for this task, unless there's some other requirement you've left out.
Since the label contains all the area that you want the click handler to affect, it should just work as is (clicking anywhere in the pink box will cause the radio button to become selected).
.form-group {
background-color: pink;
}
<div class="form-group">
<label style="font-weight:800;">chose
<input type="radio" value="z6" class="hotelObj" name="hotelType">
<p>description</p>
</label>
</div>
Your code is not working because you are using .closest() jquery method which will look for element starting from itself and then up in DOM tree.
This way element with class.hotelObj is never found.
You need to use .find() method to find .hotelObj, because it's inside .form-group.
$(".form-group").click(function() {
$(this)
.find(".hotelObj")
.trigger("click");
});
Try onClickHandled property
<input type="checkbox" onclick="onClickHandler()" id="box" />
<script>
function onClickHandler(){
var chk=document.getElementById("box").value;
//use this value
}
</script>

Change the style of a dynamically added div element when user clicks on the div or its children

I am trying to change the styling of a specific div element that I .append() to the page when the user clicks on it or one of its child elements. This is the JavaScript I have so far:
var activeNote;
$(".note").click(function () {
activeNote = $(this);
activeNote.css("border", "2px solid white");
});
$(".title, .reminder").click(function () {
activeNote = $(this).parent();
activeNote.css("border", "2px solid white");
});
The String I append to the page:
"<div class='note'><input type='text' placeholder='Title...' class='title' /><textarea name='text1' class='reminder' cols='40' rows='2' placeholder='Note...'></textarea></div>";
A better way of looking at the string:
<div class="note">
<input type="text" placeholder="Title..." class="title" />
<textarea name="text1" class="reminder" cols="40" rows="2" placeholder="Note..."></textarea>
</div>
Nothing extra happens when I add this code and click on the div element so something is wrong.
Thanks in advance for any help.
In jQuery, using this inside an event handler always refers the element that is receiving the event. To act on .note when it or it's children are clicked you could use event delegation with .on():
var activeNote;
$("#note-container").on('click', '.note', function () {
activeNote = $(this);
activeNote.css("border", "2px solid white");
});
#note-container {
background: #cef;
padding: 1em;
}
.note {
margin: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="note-container">
<div class="note">
<input type="text" placeholder="Title..." class="title" />
<textarea name="text1" class="reminder" cols="40" rows="2" placeholder="Note..."></textarea>
</div>
</div>
If you add .note elements dynamically, you need to change the way you bind your events
From
$(".note").click(function () { ... });
$(".title, .reminder").click(function () { ... });
To
$(document).on('click', '.note', function () { ... });
$(document).on('click', '.title, .reminder', function () { ... })
This way, even elements inserted to the DOM after the event handler is defined will be subject to the event handler.
js fiddle

Change class group of buttons

I have three buttons and each one has a CSS class. At click of one of them, i would like remove the class and add a new CSS class only for the clicked element. Furthermore, I need to keep pressed the selected button.
I searched some examples and I found that is possible do something like this:
$(".class").removeClass("choice").addClass("active");
This works for all buttons, but not only for one. I try to change this in
$(this).removeClass("choice").addClass("active");
but this didn't work.
I make a fiddle for more compreansion: https://jsfiddle.net/90u6b3tj/3/
EDIT
I need the same behavior when i press a second time
Sorry for the basic problem.
Thanks in advance
Regards
I've updated your jsfiddle for a working solution:
https://jsfiddle.net/90u6b3tj/10/
Here's the javascript part:
$(function() {
$("button").click(function(e) {
e.preventDefault();
$(this).toggleClass("active");
});
});
as you are adding your click events like so:-
<button id="hourly" class="choice" onclick="change()">Orario</button>
you could use event.target:-
function change(){
event.preventDefault();
$(event.target).removeClass("choice").addClass("active");
}
OR, change your event and pass in this:-
<button id="hourly" class="choice" onclick="change(this)">Orario</button>
so you can do:-
function change(element){
event.preventDefault();
$(element).removeClass("choice").addClass("active");
}
OR better still:-
$('.choice').click(function(e){
e.preventDefault();
$(this).removeClass("choice").addClass("active");
});
and remove the inline click event.
You can use the following code instead.
$(".class").click(function(){
$(".class").addClass("choice");
$(".class").removeClass("active");
$(this).removeClass("choice").addClass("active");
});
Here, the "choice" class is removed only from the clicked class. Not from the others. Also the "active" class is added to the clicked one.
You may use change(this) in your button markup and refer to that element in your change() function, as shown in this fiddle.
function change(event){
event.preventDefault();
//$(".choice").removeClass("choice").addClass("active");
$(event.target).removeClass("choice").addClass("active");
}
<div>
<button id="hourly" class="choice" onclick="change(event)">Orario</button>
</div>
<div>
<button id="daily" class="choice" onclick="change(event)">Giornaliero</button>
</div>
<div>
<button id="monthly" class="choice" onclick="change(event)">Mensile</button>
</div>
Should it possible so select more than one item as active?
If not, checkout this:
Markup
<div>
<button id="hourly" class="choice">Orario</button>
</div>
<div>
<button id="daily" class="choice">Giornaliero</button>
</div>
<div>
<button id="monthly" class="choice">Mensile</button>
</div>
CSS
.active {
background-color: #A60076;
color: #FF0000;
}
.choice {
background-color: #000000;
color: #FFFFFF;
}
JS
$(document).ready(function() {
$('button').click(function(e) {
$("button").addClass('choice').removeClass('active');
$(this).removeClass('choice').addClass('active');
});
});
Here is a sample fiddle with the above code working.

DIV losing focus when clicking on elements inside it

Why does the DIV lose focus when i click on elements inside it?
I have an JS that hides the DIV when it loses focus. But that should not happen when clicking on elements inside the DIV.
It needs to be done with .on because there is some ajax loading going on.
$(document).on('focusout', '#geomodal', function(e) {
console.log('.focusout');
});
<div id="geomodal" tabindex="-1">
<input value="109" name="districts[]" type="checkbox">
<label>Bla</label>
<br>
<input value="152673" name="districts[]" type="checkbox">
<label>Blabla</label>
<br>
</div>
http://jsfiddle.net/2g41su81/2/
jQuery Documentation:
The focusout event is sent to an element when it, or any element
inside of it, loses focus.
Only one element has focus at a time - if an input has focus, your div doesn't. After losing focus, check if the newly-focused element is your div or a child, and don't hide it in that case.
$(document).on('focusout', '#geomodal', function (e) {
setTimeout(function(){
var focus=$(document.activeElement);
if (focus.is("#geomodal") || $('#geomodal').has(focus).length) {
console.log("still focused");
} else {
console.log(".focusout");
}
},0);
});
The setTimeout is necessary to allow the new element to gain focus before doing the check.
http://jsfiddle.net/2g41su81/5/
you can also use e.relatedTarget to get the element which caused the focusout to be triggered and do handling according to that!
check this example.
the focusout event is not execute while click on inner elements
Check the "tabindex" attribute, is the trick
Html Code
<div id="mydiv" tabindex="100">
<div class="anotherdiv">
<input type="checkbox" name="" value=1>
</div>
<div class="anotherdiv"> child content
<input type="checkbox" name="" value=1>
</div>
</div>
http://jsfiddle.net/tierrarara/kPbfL/425/
JS Code
$("#mydiv").focusin(function() {
$("#mydiv").css("background","red");
});
$("#mydiv").focusout(function() {
$("#mydiv").css("background","white");
});
CSS Code
#mydiv{
width : 50px;
height:auto;
border : 1px solid red;
}
.anotherdiv{
width : 50px;
height:50px;
border : 1px solid blue;
}

Toggle parent class of checkbox on check action using jquery

I am trying to make a form with multiple checkboxes. I want to highlight the checkboxes with their content to indicate to the user of the selection
I am using the following layout for my form
HTML
<form>
<div class=labl>
<input type=checkbox id='alpha' />
<label for='alpha'>Checkbox1</label>
</div>
CSS
.labl{
height:50px;
}
.labl:hover{
background:#ccc;
}
.chked {
background: #4285f4;
height:50px;
}
jQuery
<script>
$("input[type=checkbox]").change(function() {
$(this).parent().toggleClass("chked");
});
</script>
Now when alpha is checked it should change the class of div from labl to chkedbut it is not
You need a DOM ready handler like this $(function(){...});
$(function () {
$("input[type=checkbox]").change(function () {
$(this).parent().toggleClass("chked");
});
});
Documentation
Update
It appears that the checkbox is dynamically added to the DOM so you must use event delegation like this
$(document).on("change","input[type=checkbox]",function () {
$(this).parent().toggleClass("chked");
});
You can pass both the class names to the toggleClass() method, so that only one of the will be applied at a time
jQuery(function(){
$("input[type=checkbox]").change(function() {
$(this).parent().toggleClass("labl chked");
});
})
Demo: Fiddle
just change your script to
$("input[type=checkbox]").change(function() {
$(this).parents('.labl').toggleClass("chked");
});
And your HTML to
<form>
<div class='labl'>
<input type='checkbox' id='alpha'></input>
<label for='alpha'>Checkbox1</label>
</div>
Here is the updated fiddle
http://jsfiddle.net/k242J/
toggleClass functionality is to check the class, if not there it will add, else remove class thats it. its not to change from one class to another.
css
.chked {
background: #4285f4;
}
js
$("input[type=checkbox]").change(function() {
$(this).parent().toggleClass("chked");
});

Categories

Resources