onclick fires only once when trying to change checked attribute - javascript

I want to change of status of an input checkbox when click on another element.
But click triggers only once that code block.
#menu-state:checked {
background: red;
}
#menu-state {
background: blue;
}
<input type="checkbox" id="menu-state" class="menu-state">
<a href="#menu-state" role="button" class="menu-anchor menu-anchor-open"
id="menu-anchor-open"></a>
$("#menu-anchor-open").on("click", function (e) {
e.preventDefault()
if ($('#menu-state').prop('checked')) {
$('#menu-state').attr('checked', false);
} else {
$('#menu-state').attr('checked', true);
}
});
In first click, it adds checked="checked" on the input, but on another clicks, it doesnt work.
I have also tried those solutions too;
Changing a checkbox's state programmatically in dashcode
Checkbox click function is not working
Setting "checked" for a checkbox with jQuery
jquery check all input:checkbox on button click
What am i missing?
For example below works on every click. But previous one doesnt work.
$("#menu-anchor-open").on("click", function (evt) {
evt.preventDefault()
if ($('#menu-state').hasClass('open')) {
$('#menu-state').removeClass('open');
} else {
$('#menu-state').addClass('open');
}
});

Related

jquery event are not triggered automatically

I have 2 radio buttons that will do something when either is checked. And here is a JQuery that is tied to them:
$('input[name=24hours]:radio').on('change', function() {
if($('#hours24y').is(':checked'))
{ $('table').hide(); }
else if ($('#hours24n').is(':checked'))
{ $('table').show(); }
Also in the form I have a reset button. I tried to trigger the event above when the reset button is clicked like so:
$('[type=reset]').on('click', function(){
$('input[name=24hours]:radio').triggerHandler('change');
});
The problem is, when the reset button is click for the first time, it only change the radio button to its initial state. The trigger jquery will only happen when the reset button is clicked again.
So, how can I make the trigger jquery automatically run on first click of reset button?
EDIT: Here's the example of action. When I check on the radio button #hours24n, a table will be shown. and if I check on the radio button #hours24y, the same table will be hidden.
let's say initially, the table is shown with #hours24n is checked. Then, I check on #hours24y thus the table will be hidden. Now, what I expect after clicking the reset button is, #hours24n will be checked and at the same time, the table will be shown again.
Try adding closing bracket, parentesis to change handler }) , utilizing selector 'input[name=24hours][id=hours24n]:radio' , setting .prop("checked", true) before calling .triggerHandler('change') at click event , calling .click() event to set #hours24n intially checked
$(function() {
$('input[name=24hours]:radio').on('change', function() {
if ($('#hours24y').is(':checked')) {
$('table').hide();
} else if ($('#hours24n').is(':checked')) {
$('table').show();
}
})
$('[type=reset]').on('click', function() {
$('input[name=24hours][id=hours24n]:radio')
.prop("checked", true).triggerHandler('change');
}).click();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="radio" name="24hours" id="hours24y" />
<input type="radio" name="24hours" id="hours24n" />
<input type="reset" />
<table>
<tbody>
<tr>
<td>
checked
</td>
</tr>
</tbody>
</table>
jQuery
$('input').on('change', function() {
if ($('.radio[name=24hours]').is(':checked')) {
{
$('.table').fadeTo(500, 1);
this.checked = false;}
if($('#hours24n').is(':checked'))
{
$('.table').fadeOut(500, 0);
this.checked = false; }
}
});
Try that, then create your table with the class 'table', saves the hassle if you need to apply more tables without using this method. Format your cells within;
<table class="table" style="opacity: 0"></table>

How can I toggle a radio button's checked state with jQuery?

As can be seen here, I've got this HTML:
<input type="radio" id="radbtnEmp" >rad btn</input>
...and this jQuery:
$('#radbtnEmp').click(function () {
alert("radbtnEmp clicked");
});
The alert does display when I click the radio button; However, clicking the radio button a second time does not toggle its state back to unchecked. How can I do that in jQuery?
I want to be able to respond to its state like this (or something similar):
if ($('#radbtnEmp').attr('checked', true)) {
// do stuff
} else {
// do other stuff
}
...but if the radiobutton is never checked/false, that doesn't work.
the radio buttons cannot be checked and unchecked..
For that you need to use checkboxes:
Html:
<input type = "checkbox" id = "myCheckBox">I am CheckBox</input>
jQuery:
$('#myCheckBox').on('click', function() {
if ($('#myCheckBox').is(':checked')) {
// code
}
else {
// code
}
})
Hope this helps

Trigger functions from checkbox on click by clicking on a button

I have a couple of checkboxes and a button. When I click on checkbox - function is triggered. This is the desired behavior but I want to trigger it by clicking on the button. I want to have the possibility to first select checkboxes (I tried with return false and event.preventDefault but these completely switch the selection off) and then by clicking the button - trigger functions from checkboxes. Here is a link to jsfiddle:
http://jsfiddle.net/j93k2xns/6/
So for instance: I can select 3 checkboxes (nothing should happen) and after I click the button - three alerts should appear.
The code:
HTML:
<input type="checkbox" name='check[]' id="first">first</input>
<input type="checkbox" name='check[]'>second</input>
<input type="checkbox" name='check[]'>third</input>
<input type="checkbox" name='check[]'>fourth</input>
<input type="button" value="validate" id="val-button">
JS:
var check_state;
$(document).on('click','input[name="check[]"]', function(e){
if(check_state === true) {
alert('a');
} else {
return false;
}
});
$(document).on('click','#val-button', function(){
check_state = true;
});
There are a few interpretations to his question. If I'm reading it correctly, he wants to bind an arbitrary function to the checkboxes. Clicking the button should fire this event. This is how you can achieve that using custom events in jQuery:
$(function () {
$("input[name='check[]']").bind("myCustomButtonClick", function() {
if(this.checked) {
alert('a');
}
});
})
$(document).on('click','#val-button', function(){
$("input[name='check[]']").trigger("myCustomButtonClick");
});
And the associated jsfiddle: http://jsfiddle.net/3yf7ymos/
$(document).on('click','#val-button', function(){
$( 'input[name="check[]"]' ).each(function( index ) {
if($(this).is(':checked')) {
alert("a");
return true;
}
});
});
If you want to do something when the user checks a checkbox, add an event listener:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
If the idea is run a couple of functions after the inputs are checked by clicking on a button:
function myFunction() {
if ($('input[id="something"]:checked').length == 0) {
// do something
} else if ($('input[id="something_2"]:checked').length == 0) {
// do something
}
//and so on..
}
$('#val-button').click(function() {
myFunction();
});
I have a similar inquiry. I have a number of check boxes. Each checkbox is linked to a different URL that opens a PDF form. I want my team to be able to select which forms they need by ticking the checkbox. Once they have done that, I would like a button to trigger the opening of each form based on which check box is checked. I have it so the checkbox upon being checked opens the form right away but it is very distracting. Its preferable they all get opened at once by a "button". Help. I am quite new to JavaScript so may need additional clarity.

How to trigger a click event on disabled elements

I have a disabled button, which is enabled after checking "I accept terms and conditions" checkbox.
The problem is that I wanted to trigger an alert, if a user clicks the disabled button. How can I do this? If an element is disabled, it looks as "onclick" events are not fired.
The sample of the code:
<input id="subm_tc" class="btn btn-primary" type="submit" disabled="" value="Log in" name="Submit">
$("#subm_tc").click(function () {
if($("#modlgn-tc").is(':checked')){
alert('checked');
} else {
alert('unchecked');
}
});
If I wrap the element in div and listen to clicks on that div, it works, but you need to click outside the button.
How can I fix this?
Thanks
UPDATE. I've managed to resolve this by adding a fake div over the submit button and listening to events on that div (I also change z-index to -200 to enable clicks on the button itself):
<div style="position:relative">
<div id="subm_tc" style="position: absolute; left: 0px; right: 0px; bottom: 0px; top: 0px; z-index: 99999;"></div>
<input id="subm_tc" class="btn btn-primary" type="submit" disabled="" value="Log in" name="Submit">
</div>
Now it works as intended
My solution was to put the button in a div, which is clickable. when the button is disabled, the div has the width and height of the button, so clicking the button triggers the div. when the button is enabled, the div is shrunk to 0 width 0 height, so the click event registers with the button instead of the div. This code includes some demoing code as well for a toggle button which toggles the enabled/disabled state of the button in question
fiddle: http://jsfiddle.net/6as8b/2/
HTML
Click 'Toggle" to make 'Button' enabled or disabled. click it, and see that that one event fires if it is enabled, and another if disabled.
<input type=button value='toggle' id='toggle'><BR>
<div style='position:relative'>
<div id='clickable'></div>
<input id=theButton type=button disabled value='Button'>
</div>
<div id=clicks></div>
CSS
#clickable{
position:absolute;
width:55px;
height:25px;
}
JS
$(document).ready(function () {
$('#clickable').on('click',function () {
if ($('#theButton:disabled').length>0)
{
$('#clicks').append('|Disabled Button Clicked|<br>');
}
else
{
//do nothing and let the button handler do it
$('#theButton').click();
}
});
$('#theButton').on('click',function() {
$('#clicks').append('|ENABLED button clicked|<br>');
});
$('#toggle').on('click',function() {
if ($('#theButton:disabled').length>0)
{
$('#theButton').removeAttr('disabled');
$('#clickable').css({'width':'0px','height':'0px'});
}
else
{
$('#theButton').attr('disabled','disabled');
$('#clickable').css({'width':'55px','height':'25px'});
}
});
});
Disabled elements doesn't trigger any mouse events at all, so that's probably a lost cause.
However, when clicking a parent element, the event.target seems to be given correctly, which means this should work :
$(document).on('click', function (e) {
if (e.target.id == 'subm_tc') {
if($("#modlgn-tc").is(':checked')){
alert('checked');
} else {
alert('unchecked');
}
}
});
FIDDLE
You can write a function that adds listeners to the mousedown and mouseup events, and if the targets match your Node (i.e. the mousedown and following mouseup were on your element), then it invokes another function
function listenFullClick(elm, fn) {
var last;
document.addEventListener('mousedown', function (e) {
last = e.target === elm;
});
document.addEventListener('mouseup', function (e) {
if (e.target === elm && last) fn();
});
};
listenFullClick(
document.getElementById('foo'), // node to look for
function () {alert('bar');} // function to invoke
);
DEMO
Old topic, but here are my two cents as I had the same challenge lately:
Don't try to position a clickable element above it but wrap it with one so you won’t directly be able to click it. Assuming a button with display: inline-block set:
<span class="on-disabled">
<input id="subm_tc" class="btn btn-primary" type="submit" disabled value="Log in" name="Submit">
</span>
Define you click event for the case of the button being disabled:
$('.on-disabled').click(function (ev) {
// Don’t react to click events bubbling up
if (ev.target !== ev.currentTarget) return;
// Do your thing
alert('Sorry, this button is disabled');
});
And simply style the button like:
#subm_tc {
display: inline-block;
}
#subm_tc[disabled] {
position: relative;
z-index: -1;
}
This allows you to easily react to a click even in case of a disabled button.
See FIDDLE.
If you use Twitter Bootstrap, they give you a class disabled that provides the styling but doesn't remove the click event. Given that, what I did was this (keep in mind also, I wanted to be sure that when the button was no longer disabled, the original click event did fire, and I didn't want to deal with unbinding, rebinding it).
function disableButton(btn, message) {
btn.addClass("disabled")
if (!(message == null || message == "")) {
btn.data("message", message)
}
}
function enableButton(btn) {
btn.removeClass("disabled")
}
$("#btn").click(function() {
if (!($(this).hasClass("disabled"))) {
// original, desired action
} else {
message = $(this).data("message")
if (!(message == null || message == "")) {
alert(message)
}
}
})
2022 Update: I know this is an old question, but here's an update after evaluating various solutions, including CSS position:absolute and pointer-events:none
The disadvantage of simulating the disabled look ("Pretend Disable") was that, back then, various browsers presented disabled elements differently. That's not as true today because Chrome, Edge, Firefox, and other modern browsers, implement disabled button inputs (and likely other inputs) with the equivalent of opacity .5 .
The solution below is inspired by https://css-tricks.com/making-disabled-buttons-more-inclusive which uses the aria-disabled attribute in place of the older disabled attribute. That article strongly advised against using CSS techniques such as position:absolute and pointer-events:none, because when disabled, the input (or underlying/overlying element) cannot receive focus preventing the possibility of an automatic tooltip when tabbed to and preventing a screen reader from announcing the element is disabled.
Accessible Rich Internet Applications (ARIA) is a set of attributes that define ways to make web content and web applications (especially those developed with JavaScript) more accessible to people with disabilities.
HTML:
<input type='button' id='toggle' value='Toggle'>
<input type='button' id='theButton' value='Button'>
<div id='clicksReport'></div>
Plain JavaScript:
document.querySelector('#theButton').onclick = function () {
if (document.querySelector('#theButton').ariaDisabled)
{
// Your disabled button code (if any)
document.querySelector('#clicksReport').insertAdjacentHTML("beforeend",'|Disabled Button Clicked|<br>');
}
else
{
// Your emabled button code
document.querySelector('#clicksReport').insertAdjacentHTML("beforeend",'|ENABLED button clicked|<br>');
}
}
document.querySelector('#toggle').onclick = function() {
if (document.querySelector('#theButton').ariaDisabled)
{
// If not a button input, also remove the readOnly attribute
var el = document.querySelector('#theButton');
el.ariaDisabled = null;
el.style.opacity = null;
}
else
{
// If not a button input, also set the readOnly attribute
var el = document.querySelector('#theButton');
el.ariaDisabled = true;
el.style.opacity = '.5';
}
}
JS Fiddle: https://jsfiddle.net/SKisby/3Lna8q7h/7/
The same in d3 (as that's what I'm currenlty using and it's similar to jQuery):
d3.select('#theButton').on('click',function () {
if (d3.select('#theButton').attr('aria-disabled'))
{
// Your disabled button code (if any)
d3.select('#clicksReport').node().insertAdjacentHTML("beforeend",'|Disabled Button Clicked|<br>');
}
else
{
// Your emabled button code
d3.select('#clicksReport').node().insertAdjacentHTML("beforeend",'|ENABLED button clicked|<br>');
}
});
d3.select('#toggle').on('click',function() {
if (d3.select('#theButton').attr('aria-disabled'))
{
// If not a button input, also remove the readOnly attribute
d3.select('#theButton').attr('aria-disabled',null)
.style('opacity',null);
}
else
{
// If not a button input, also set the readOnly attribute
d3.select('#theButton').attr('aria-disabled',true)
.style('opacity','.5');
}
});
d3 Fiddle: https://jsfiddle.net/SKisby/qkvf3opL/2/
The above are simple, both have the same disabled look in Chrome, Firefox, and other modern browsers, and have the benefits of being able to receive focus (where an automatic tooltip could then be implemented and ARIA screen readers can convey the element is effectively disabled).
If the input is not a button, also set and remove the readOnly attribute.

jquery stopPropogation() not working as expected

here is my html :
<span class="checkbox checked replacement" tabindex="0">
<span class="check-knob"></span>
<input type="checkbox" name="data[InfoPagesClient][3][info_page_id]" value="25" checked="checked" class="">
</span>
<label for="InfoPagesClient3InfoPageId" class="label">asdasd</label>
now I want to show hide this pencil box on checkbox click event..
javascript :
$("p.checkbox-group span.checkbox").on('click', function(){
if($(this).hasClass('checked')) {
$(imgId).hide();
} else {
console.log('aaaaaaaaaaa');
$(imgId).show();
}
});
$("label.label").on('click', function(e) {
if ($(this).siblings('span.checkbox').hasClass('checked')) {
$(imgId).hide();
} else {
$(imgId).show();
}
e.stopImmediatePropagation();
});
clikcing on label it is going to span click event and prints console value... I tried using e.stopPropogation() and stopImmediatePropogation().. but ti is not working..
any idea ??
e.stopPropogation() or e.stopImmediatePropogation() will prevent the event from bubbling up, but will not stop the event immediately.
You can use e.preventDefault() along with e.stopPropogation(). e.preventDefault() will prevent the default event from occurring. You can check with the following change in your code.
$("p.checkbox-group span.checkbox").on('click', function(e){
e.preventDefault();
e.stopPropagation();
if($(this).hasClass('checked')) {
$(imgId).hide();
} else {
console.log('aaaaaaaaaaa');
$(imgId).show();
}
});
$("label.label").on('click', function(e) {
e.preventDefault();
e.stopPropagation();
if ($(this).siblings('span.checkbox').hasClass('checked')) {
$(imgId).hide();
} else {
$(imgId).show();
}
});
When you use label with for, browser will automatically click the associated control which triggers the "click" event. That is another event triggered later, in your case when you use e.stopImmediatePropagation();, it just stops the current "click" event and has no effect on the event of the associated control fired after that
To fix your issue, try removing for
Use this:
<label class="label">asdasd</label>
Instead of:
<label for="InfoPagesClient3InfoPageId" class="label">asdasd</label>
If you add the id attribute to your checkbox, then the label will work. Then you can simplify your code as follows:
$(function () {
$("p.checkbox-group input[type=checkbox]").on('change', function () {
if (this.checked) {
$(this).parent().addClass('checked').siblings('a.edit-content').hide();
} else {
$(this).parent().removeClass('checked').siblings('a.edit-content').show();
}
});
});
http://jsfiddle.net/gFXcm/2/
mmmh, isn't it a feature instead of a bug ? shouldn't the click on the label trigger the same action as the click on the "checkbox" ? That's precisely why the for attribute is used I guess.

Categories

Resources