I want an event to fire client side when a checkbox is checked / unchecked:
$('.checkbox').click(function() {
if ($(this).is(':checked')) {
// Do stuff
}
});
Basically I want it to happen for every checkbox on the page. Is this method of firing on the click and checking the state ok?
I'm thinking there must be a cleaner jQuery way. Anyone know a solution?
Bind to the change event instead of click. However, you will probably still need to check whether or not the checkbox is checked:
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});
The main benefit of binding to the change event over the click event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change event. Redacted in comments
Also note that I've used this.checked instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.
Edit (see comments)
To get all checkboxes you have a couple of options. You can use the :checkbox pseudo-selector:
$(":checkbox")
Or you could use an attribute equals selector:
$("input[type='checkbox']")
For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answer above will not work. You'll need to leverage event delegation which allows a parent node to capture bubbled events from a specific descendant and issue a callback.
// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
if(this.checked) {
// checkbox is checked
}
});
Note that it's almost always unnecessary to use document for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.
The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.
$postList = $('#post-list');
$postList.find('h1').on('click', onH1Clicked);
function onH1Clicked() {
alert($(this).text());
}
// simulate added content
var title = 2;
function generateRandomArticle(title) {
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}
setTimeout(generateRandomArticle.bind(null, ++title), 1000);
setTimeout(generateRandomArticle.bind(null, ++title), 5000);
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
<article class="post">
<h1>Title 1</h1>
</article>
<article class="post">
<h1>Title 2</h1>
</article>
</section>
While this example displays the usage of event delegation to capture events for a specific node (h1 in this case), and issue a callback for such events.
$postList = $('#post-list');
$postList.on('click', 'h1', onH1Clicked);
function onH1Clicked() {
alert($(this).text());
}
// simulate added content
var title = 2;
function generateRandomArticle(title) {
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
<article class="post">
<h1>Title 1</h1>
</article>
<article class="post">
<h1>Title 2</h1>
</article>
</section>
Just another solution
$('.checkbox_class').on('change', function(){ // on change of state
if(this.checked) // if changed state is "CHECKED"
{
// do the magic here
}
})
If your intention is to attach event only on checked checkboxes (so it would fire when they are unchecked and checked later again) then this is what you want.
$(function() {
$("input[type='checkbox']:checked").change(function() {
})
})
if your intention is to attach event to all checkboxes (checked and unchecked)
$(function() {
$("input[type='checkbox']").change(function() {
})
})
if you want it to fire only when they are being checked (from unchecked) then #James Allardice answer above.
BTW input[type='checkbox']:checked is CSS selector.
Is very simple, this is the way I use:
JQuery:
$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
var checkbox = $(this), // Selected or current checkbox
value = checkbox.val(); // Value of checkbox
if (checkbox.is(':checked'))
{
console.log('checked');
}else
{
console.log('not checked');
}
});
Regards!
$(document).ready(function () {
$(document).on('change', 'input[Id="chkproperty"]', function (e) {
alert($(this).val());
});
});
This is the solution to find is the checkbox is checked or not.
Use the #prop() function//
$("#c_checkbox").on('change', function () {
if ($(this).prop('checked')) {
// do stuff//
}
});
It can also be accomplished as below. When the checkbox is fired, the div
or control with #checkbox id is hiddden or is shown otherwise.
<script>
$('#checkbox').on('click',function(){
if(this.checked){
$('#checkbox').hide();
}else{
$('#checkbox').show();
}
});
</script>
Action taking based on an event (on click event).
$('#my_checkbox').on('click',function(){
$('#my_div').hide();
if(this.checked){
$('#my_div').show();
}
});
Without event taking action based on current state.
$('#my_div').hide();
if($('#my_checkbox').is(':checked')){
$('#my_div').show();
}
Try this "html-approach" which is acceptable for small JS projects
function msg(animal,is) {
console.log(animal, is.checked); // Do stuff
}
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
...
perhaps this may be an alternative for you.
<input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`
Try this jQuery validation
$(document).ready(function() {
$('#myform').validate({ // initialize the plugin
rules: {
agree: {
required: true
}
},
submitHandler: function(form) {
alert('valid form submitted');
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<form id="myform" action="" method="post">
<div class="buttons">
<div class="pull-right">
<input type="checkbox" name="agree" /><br/>
<label>I have read and agree to the Terms of services </label>
</div>
</div>
<button type="submit">Agree</button>
</form>
the key is: use prop but not attr to query the checked status, e.g.
correct: jQuery('#my_check_tag').prop('checked') // return correct status
incorrect: jQuery('#my_check_tag').attr('checked') // always return undefined
Related
I want to use jquery to always hide an element when it is checked, and show the element when it is unchecked. After doing some research I found the "is" attribute and so I created a simple html file as:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
if($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p id="test">This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<input type="checkbox" id="s">Click me</input>
</body>
</html>
Now for some reason, the jquery is not functional. Any help would be appreciated please. I also tried:
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
And this doesn't work either.
This is simple in javascript. Please try the following:
var cb = document.getElementById('isAgeSelected');
var txtAge = document.getElementById('txtAge');
$(document).ready(function(){
cb.change= function(){
if(cb.checked) {
txtAge.style.display ='block';
} else {
txtAge.style.display ='none';
}
};
});
In JQuery, you can do the following:
$(document).ready(function(){
$('#s').on('change', function(){
if($(this).is(":checked")){
$('#txtAge').show();
}
else{
$('#txtAge').hide();
}
});
});
You are only checking the checkbox once after the DOM is ready instead you should do it on its change event
$("#s").change(function(){
if($(this).is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
You can do this using following jQuery onchange event and .checked function
$(document).ready(function(){
$('#s').change(function(){
if(this.checked)
$("#test").hide(); // checked
else
$("#test").show();
});
});
Working URL:: https://jsfiddle.net/qn0ne1uz/
Good question !
now you were almost there.
$(document).ready(function(){ // <= !! you only evaluete the chackbox once (on document ready)
if($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
What you want to do is monitor checkbox the whole time, like so:
$('#s').bind('change', function() {
if ($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
example on jsfiddle
I'm guessing you are wanting to use the jQuery when the checkbox changes - at the moment you are just changing the hide / show it when the document loads.
Also ids need to be unique or jQuery will only get the first item with that id it comes to when you use the id selector. Change the test id to a class.
If you want the click me to change the state of the checkbox, turn it into a label (think you had it as a button) and target the input (using either for="input-id or wrap the label around the input and the text)
Try the following:
// this is to go in your document ready
$('#s').on('change', function() { // bind to the change event of the chackbox
// inside any change event, this is the js object of the thing that changed (ie the checkbox)
if (this.checked) {
$('.test').hide();
} else {
$('.test').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>This is a heading</h2>
<!-- ids need to be unique so change this to a class or your jquery won't work -->
<p class="test">This is a paragraph.</p>
<p class="test">This is another paragraph.</p>
<input type="checkbox" id="s"><label for="s">Click me</label>
My function works as it should. is there a way to remove the function from a specific input? Because it changes all inputs.. i have 2 check boxes and 1 input that i need to not have this function on.
$('input').blur(function(){
$('input').parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
Try adding a class to the input and checkbox that you don't want the onblur functions, then update the code as below
Add the class to the three inputs that you don't want this feature
$('input').not( ".class" ).blur(function() {
$(this).parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
Hope this helps what you need.
Use this context, $('input') will select all the <input> elements, this in the callback will hold the element on which event is invoked!
$('input').blur(function() {
$(this).parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
.gray {
background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>
<input type="text">
</div>
<div>
<input type="text">
</div>
If you have id's for those three inputs you can use this code snippet.
$('input').blur(function(){
$(this).parent().removeClass("gray");
})
.focus(function() {
$(this).parent().not( "#id1, #id2, #id3" ).addClass("gray")
});
It will add class to those inputs which do not match the selector.
I have a jQuery click event which adds a class (active) to a dropdown.
In the dropdown there are boxes (with the class generically called box).
Currently the jQuery event fires anytime you click anywhere in the item class, but if you click the box it also closes the dropdown. Thus I am adding an if statement above the addClass part which checks if you clicked a box.
Here's the html:
<div class="trainee-item">
<div class="dropdown">
<div class="box"></div>
</div>
</div>
and here's the JS:
$('.item').click(function(e) {
$('.box').click(function() {
console.log('stop!!!');
});
if ($(this).children('.dropdown').hasClass('active')) {
$(this).children('.dropdown').removeClass('active');
return;
}
$(this).children('.dropdown').addClass('active');
});
I've tried return (where the console.log('stop!!!!'); currently is, but that only stops the $('.box').click(function() (the immediate "parent" function). I am trying to stop the function above that one
Any help? thanks
One way would be
$('.item').click(function(e){
if (e.target.className=="box"){
e.preventDefault()
return
}
})
$('.item').click(function(e) {
if (e.target.className=="box"){
e.preventDefault()
alert("don't close it!")
return
}
if ($(this).children('.dropdown').hasClass('active')) {
$(this).children('.dropdown').removeClass('active');
return;
}
$(this).children('.dropdown').addClass('active');
});
.dropdown{display:none;width:100px;height:100px;background:#bbb}
.active{height:120px;}
.item{height:20px;background:#ccc}
.active.dropdown{display:block}
.box{border-bottom:1px solid #999;padding:10px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="trainee-item item">
<div>Click me</div>
<div class="dropdown">
<div class="box">hi</div>
</div>
</div>
You should separate these into separate click events. You should also delegate them, since you'll trigger both due to event bubbling. It's been a while since I've written jQuery, but from what I remember you should be using .on();, since you can delegate with that method.
I'll leave the delegation as homework for you, but here's how you should be approaching this issue:
$('.item').on('click', function(e, el) {
var $child = $(this).children('.dropdown'),
activeClass = 'active';
$child.hasClass(activeClass) ? $child.removeClass(activeClass) : $child.addClass(activeClass);
});
$('.box').on('click', function(e, el) {
console.log('box clicked');
});
I am trying to check whether or not a particular element has been clicked but am having trouble doing so. Here is my HTML:
<div id="my_special_id" class="switch switch-small has-switch" data-on="success" data-off="danger">
<div class="switch-on switch-animate"><input type="checkbox" checked="" class="toggle">
<span class="switch-left switch-small switch-success">ON</span>
<label class="switch-small"> </label>
<span class="switch-right switch-small switch-danger">OFF</span>
</div>
</div>
Here is my jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
</script>
I am guessing that my id "my_special_id" is not what is actually being clicked?
I guess click event should have event parameter.
$(document).ready(function() {
$('#my_special_id').click(function(e) {
if (e.target check condition) {
window.alert('ON!');
}
});
});
parameter 'e' above specified is the event object that has all info about click event.
so if u check all info under 'e.tartget', u will be able to find out which one is clicked.
Hope it's helpful for you.
Cheers :)
Since you are looking for a alert when the checkbox is clicked
$(document).ready(function() {
$('#my_special_id input.toggle').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
Demo: Fiddle
Simply put alert when you click on that particular class switch-on
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id div:first-child .switch-on').on('click',function() {
window.alert('ON!');
});
});
</script>
Or even try like
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($(this + 'div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
This JavaScript works for me.
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
alert("On!");
}
});
});
You are sure you have JQuery?
Your code looks fine I think either you have a syntax error somewhere else or you do not have JQuert.
does this alert?
$(document).ready(function() {
alert("Jquery works");
});
The click event will trigger to whatever you're bound do. the only time you'd have to be worried is if you bound to both a parent and child (e.g. you had listed #my_special_id,.switch-small--then you'd have to look at e.target).
With that said, you can use scope to limit how jQuery finds the div:first-child. I'm not 100% sure what you're after, but the below appears to do what you're after:
$(document).ready(function() {
$('#my_special_id').click(function() {
// look for div:first-child within `this` (where `this=#my_special_id`
// per the .click selector above)
if ($('div:first-child',this).hasClass('switch-on')) {
window.alert('ON!');
}
});
});
If you're looking to bind to the on/off separately, you may want to change it around a bit. we can still check for .switch-on, just have to traverse differently:
// here we bind to the on/off buttons and not the container
$('#my_special_id .switch-small').click(function(){
// you want the facsimilee of `div:first-child`, so (because we're now
// within that node, we use .parent() to get back up to it
var $firstChild = $(this).parent();
if ($parent.hasClass('switch-on')){
alert('ON!');
}
});
newbie here. I am trying to used jquery wrapInner to show the next choice for the user while trying to hide the original element. Here is my jsfiddle.
Once I click endorse radio button it hide the elements in between . The cancel button show the elements back. But clicking endorse radio button again nothing happen.
Any help on this would be more than appreciated !
html:
<div id="engr-action" >
<div id="engr-choice">
<input id="endorse" class="engr-choice" type="radio" name="encoder-pick"/>
<label for="endorse">ENDORSEMENT</label>
<input id="encode" class="engr-choice" type="radio" name="encoder-pick"/>
<label for="encode">ENCODE</label>
</div>
<button id="cancel-action">Cancel</button>
</div>
jquery:
$(function(){
$('#engr-choice').buttonset();
$('#cancel-action')
.button()
.click(function() {
$('#engr-choice').html('');
$('#endorse-edit').hide();
$('#engr-choice').wrapInner('<input id="endorse" class="engr-choice" type="radio" name="encoder-pick"/><label for="endorse">ENDORSEMENT</label>');
$('#engr-choice input').removeAttr('checked');
$('#engr-choice').buttonset('refresh');
return false;
});
$('#endorse').click(function(){
$('#engr-choice').html('');
$('#engr-choice').wrapInner('<div id="endorse-edit">Edit</div>');
$('#endorse-edit').button();
return false;
});
});
Since your element is generated "on the fly", thru javascript, your $('#endorse').click(.. event wont work as that element did not exist on DOM, so in order to add events to your elements, created on the fly, you would need to use event delegation, so
change:
$('#endorse').click(function(){
..
to
$(document).on('click', '#endorse',function(){
...
See:: Updated jsFiddle
You can try this: Fiddle setup
$(function () {
$('#engr-choice').buttonset();
$('#cancel-action').button().click(function () {
$('#engr-choice').html('');
$('#endorse-edit').hide();
$('#engr-choice').append('<input id="endorse" class="engr-choice" type="radio" name="encoder-pick"/> <label for="endorse">ENDORSEMENT</label>');
$('#engr-choice input').prop('checked', false);
return false;
});
$('#engr-action').on('click', '#endorse', function () {
$('#engr-choice').html('');
$('#engr-choice').wrapInner('<div id="endorse-edit">Edit</div>');
$('#endorse-edit').button();
});
});
As you are putting html elements via javascript/jQuery so direct binding of events won't be available for them, so you need to do it via event delegation that is to delegate the event to the static closest parent which is in your case is #engr-action or you can do it with $(document) which is always available to delegate the events.