Change checkbox value doesnt fire the change event in Jquery - javascript

I have a checkbox and I marked it as checked, however it doesnt fire the on change function. The note doesn't appear.
My code:
$('#checkbox1').prop("checked", true);
$('#checkbox1').change(function(){
if ($(this).is(':checked'))
$('#s-note').show();
else
$('#s-note').hide();
});

Do you expect the onchange to fire without user interaction?
Your issue is you set the checked state before you set the handler so if this would have trigged change, you would have not caught it. Your real issue here is setting the property with JavaScript does not fire the change event. So you need to trigger the change event manually.
$('#checkbox1')
.prop("checked", true) // set it to checked
.on("change", function() { // bind change event
$('#s-note').toggle($(this).is(':checked')); // toggle visibility
}).trigger("change"); //trigger that you need the change to run

If you are setting the note to be hidden by default and doing it with an id based selector, like this:
#s-note { display:none; }
Then your code won't be able to show it because it also uses an id based selector and that won't be more specific than the selector already in effect.
Instead, you'll have to default the note to hidden using a selector that is less specific than the id selector you will use to show/hide it later. That would be a class.
Also, it's critical that you set up the event handler before you trigger the event, so that when the event happens, there is already an event handler registered.
Now, for your needs, you don't really need the change event, click will do just fine. And, lastly, to ensure that you properly trigger the event, use JQuery's .trigger() method to set things in motion.
// Make sure you set up the callback first
$('#checkbox1').on("click", function(){
if ($(this).is(":checked"))
$('#s-note').show();
else
$('#s-note').hide();
});
// Then just trigger the event
$('#checkbox1').trigger("click");
.hide { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1">Test
<div id="s-note" class="hide">Special</div>

I hope this code snippet will help you
Approach 1
$('#idcheckbox').on('change', function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('default ');
}
});
Approach 2
$('input[type=checkbox]').on('change', function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('default ');
}
});

I ran your code in .net mvc and it runs fine.
This is the checkbox same id it hide or shows div element.
<input type="checkbox" id="checkbox1" value=" " />
<div id="s-note" style="display: none">
<label>Showing</label>
</div>
What are you trying to display?

Related

Too many unwanted result when calling jquery .change() function

I have a bootstrap toggle button in HTML like that:
<input id="warnbtn" type="checkbox" checked data-toggle="toggle" data-onstyle="success" data-offstyle="danger" >
and I try to catch the event of this with this script:
$(function() {
$('#warnbtn').change(function() {
var state = $(this).prop('checked')
if(state){
console.log("On");
}else{
console.log("Off");
}
})
})
My toggle is not smooth like the one in Bootstrap Toggle website
And the result I get with the .change function have lot of unwanted result like the picture here
It sounds like you are loading the same script numerous times. Every time you run that same block it adds a new change event listener and each will fire when the event occurs
You should find out why and try to prevent it
For a short term workaround you can call off() first to remove any previous event listeners that were called
Try:
$('#warnbtn').off('change').change(function() {
var state = $(this).prop('checked')
if(state){
console.log("On");
}else{
console.log("Off");
}
})
Thank u for answer my question :( I think I will replace the toggle button with another solution

jQuery Radio Button onChange Not Working

I followed this example to capture an onChange() jQuery event for a radio button group:
JQuery $(#radioButton).change(...) not firing during de-selection
But in my case, the solution given in that example is not working. I have the following generated from my JSP:
<input id="object.reportEntity.reportEntityIsPrime1" name="object.reportEntity.reportEntityIsPrime" type="radio" value="Y_YES" checked="checked"/>Prime
<input id="object.reportEntity.reportEntityIsPrime2" name="object.reportEntity.reportEntityIsPrime" type="radio" value="N_NO"/>Not Prime
JS:
$(document).ready(function() {
// Display Alert on Radio Change
$('input[name=object.reportEntity.reportEntityIsPrime]:radio').change(function () {
alert('Radio Button clicked');
});
}
The alert is not being diplayed. Also, there's this error:
Syntax error, unrecognized expression "input"
You should delegate the events.
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
Also, you need to add " in your selector e.g. [name=""] Observe the following...
$('body').on('change', 'input[name="object.reportEntity.reportEntityIsPrime"]:radio', function() {
alert('Radio Button clicked');
});
side note: you are missing ); on the end of your ready function
JSFiddle Link - working demo
Also, be sure to check out the jQuery Understanding Event Delegation docs for more info
Use quote marks for your name like this:
$('input[name="object.reportEntity.reportEntityIsPrime"]:radio')
Quote the name attribute in your selector string.
$(document).ready(function() {
// Display Alert on Radio Change
$('input[name="object.reportEntity.reportEntityIsPrime"]:radio').change(function () {
alert('Radio Button clicked');
});
}

Click on dynamically generated radio button

i am trying to alert some text when a dynamically generated radio button is checked .. here is the link from fiddle ..
http://jsfiddle.net/z7cu3q0y/
function createRadioButtons(n)
{
$("#radioContainer").empty();
for(var i=0;i<n;i++)
{
radioButtons = "<p><input type='radio' class='"+n+"' name='"+n+"'>"+(i+1)+"</p>";
$("#radioContainer").append(radioButtons);
}
}
$("#dropDown").on("change",function()
{
createRadioButtons(parseInt($(this).val()));
});
$("#radioContainer input").on("change",function()
{
alert("checked");
});
when i click on radio button i am not getting alert .. can any one of you please help me in taking a look ?
Thanks in advance,
Ashwin
Your code $("#radioContainer input").on("change",function(){})
will directly attach the event handler to the matching elements that are currently present in DOM.
To work with dynamically generated elements added in the future, You need to delegate your event handler to a common parent element:
$("#radioContainer").on("change","input",function(){
alert("checked");
});
The above will attach the handler to #radioContainer, Whenever the corresponding event (change in this case)is triggered (Usually propagated from the children), it checks whether the event target matches the specified selector (input in this case) and invokes the handler accordingly.
Updated Fiddle
You need to use .on() for dynamically generated elements like below. Here .on() will bind change event to all radio buttons which are inside radioContainer
$("#radioContainer").on("change","input[type=radio]",function()
{
alert("checked");
});
Demo
Try using the below code
$(document).on("change","#radioContainer input",function(){
alert("checked");
});
Updated fiddle
You need to put the input defined as click area and radiocontainer as working area.
DEMO: http://jsfiddle.net/don/z7cu3q0y/3/
Just remove input before .on and put inside of the function.
jQuery:
function createRadioButtons(n)
{
$("#radioContainer").empty();
for(var i=0;i<n;i++)
{
radioButtons = "<p><input type='radio' class='"+n+"' name='"+n+"'>"+(i+1)+"</p>";
$("#radioContainer").append(radioButtons);
}
}
$("#dropDown").on("change",function()
{
createRadioButtons(parseInt($(this).val()));
});
$("#radioContainer").on("change", 'input', function()
{
alert("checked");
});

checkbox jquery or javascript oncheck?

I do not know the correct terminology for this, but I want the same effect as onclick but for a check box with jquery or javascript.
onclick version:
Link
I want the same effect as above but for a checkbox. The end result will be that the page should reload with an updated php query, but that part I can do. I just don't know what the onclick is for checkboxes.
checkbox:
<input type="checkbox" name="change" value="one" />changes php query
You should listen to the change event, as the checkbox can be selected or deselect with the keyboard too:
$('input[type="checkbox"][name="change"]').change(function() {
if(this.checked) {
// do something when checked
}
});
Similarly with plain JavaScript:
// checkbox is a reference to the element
checkbox.onchange = function() {
if(this.checked) {
// do something when checked
}
};
And last, although you really should not use inline event handlers, but if you have to:
<input ... onchange="handler.call(this)" />
where handler is like the handlers shown above.
Further reading:
jQuery documentation
MDN JavaScript Guide
quriksmode.org Introduction to Events
$('#input_id').click(function() {
// do what you want here...
});
$('input:checked').click(function() {
//do something
});
See http://api.jquery.com/checked-selector/ and http://api.jquery.com/checkbox-selector/

Javascript disable button

I am wondering if someone can help me out with this.
I have a button defined as:
<input type="button" id="myButton" name="myButton" value="ClickMe!!" onClick="callMe()"/>
I can use jQuery, standard javascript or Dojo to disable the button with onClick event:
$('#myButton').attr('disabled', 'disabled');
The problem I am facing is, even though this code disables the button, onClick event still triggers the function callMe() if I click on the button.
How do I make the disabled button not call the onClick function?
With jQuery you can bind a function that checks if your button is disabled:
$('#myButton').click(function() {
if (!$(this).is(':disabled')) {
callMe();
}
});
Since you're using jQuery, use
$('#myButton').click(function() { callMe(); this.unbind(); });
instead of onClick.
$('#myButton').click(function(){
if( !$(this).is('[disabled=disabled]') ){
...
}
});
In the same code where you disable it, simply remove the onclick event handler.
instead of using onclick attribute, bind to the event
$('#myButton').click(function(e){
// try it without this
if($(this).attr('disabled'))
return false;
callMe();
e.preventDefault();
});
try it without the check, not sure if its necessary.
This is one way of doing.
$('#myButton').click(function(){
if(!$(this).hasClass("disabled")){
//Do stuff here
}
});
To disable the buttons just add the disabled class to it.
$('#myButton').addClass("disabled");
Add appropriate styles in the disabled class to make button look like disabled or you can also set the disabled property along with setting the class.
you should be using jQuery to attach the click handlers, not adding them inline*
Just add a check to your click function
$('#myButton').click(function(){
var $this;
$this = $(this);
if ( $this.is(':disabled') ) return;
callMe();
});
Alternatively,
$('#myButton').click(callMe);
callMe()
{
var $this;
$this = $(this);
if ($this.is(':disabled')) return;
...the rest of your code...
}
Or if you insist on using it inline:
onclick="if ($(this).is(':disabled')) return; callMe();"
* I regularly rant about how HTML, CSS & JS fit the definition of MVC
Instead of ...
$('#myButton').attr('disabled', 'disabled');
... use ...
$('#myButton')
.prop('disabled', 'disabled') // Sets 'disabled' property
.prop('onclick', null) // Removes 'onclick' property if found
.off('click'); // Removes other events if found

Categories