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

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

Related

Change checkbox value doesnt fire the change event in Jquery

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?

why does my button disappear when I add the toggle event in jquery?

I want to toggle text between bold and normal I made this code for it, but when I open my page the bold button disappears?
$("#bold").toggle(function() {
$('.focus').css("font-weight", $(this).val());
}, function() {
$('.focus').css("font-weight", "normal");
});
Is there something wrong with my code?
Please help, thanks in advance.
Assuming you're using jQuery 1.9 or later the problem is that the .toggle() event handling method was removed from the library. So what you're actually calling is the .toggle() function that hides/shows elements. (In earlier versions of jQuery both functions existed and jQuery figured out which one you meant based on the arguments passed in.)
You can implement your own toggle easily enough with a standard .click() handler:
$("#bold").click(function() {
var f = !$(this).data("toggleFlag");
if (f) {
$('.focus').css("font-weight", $(this).val());
} else {
$('.focus').css("font-weight", "normal");
}
$(this).data("toggleFlag", f);
});
This uses the .data() method to keep track of a boolean flag to indicate which code to execute. The very first time the click handler is called the flag will be returned as undefined because it hasn't previously been set, but we just convert that to a boolean with ! (assuming you want to execute the if and not the else case on the first click).
It disappears because that version of toggle is deprecated and removed, and in newer versions of jQuery all it does is toggle visibility.
You could do something like this instead :
var state = true;
$("#bold").on('click', function() {
$('.focus').css("font-weight", state ? this.value : 'normal');
state = !state;
});
FIDDLE
The only solution I fount to the disappearing element after click... is Callback function after the toggle effect finished.
here a link that explain the Callback function.
and here is my code:
jQuery('.menu li.item-487').click(function(){
jQuery('#main-menu .moduletable .menu li').toggle("slow",function(){jQuery('.menu li.item-487').css('display' , 'block');});
});

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

Need to add another onClick event

I have a checkbox, that is styled using onclick handler.
The issue I have is , I also want to fire a div simultaneously.. to display hidden message.
Kind of like: checkbox ( tick to go featured )
If ticked show featured div, else hide.
Code I have is:
<span id="checkboxWrap" class="styledCheckboxWrap"><input name="include" type="checkbox" id="checkbox" onclick="setCheckboxDisplay(this)" class="styledCheckbox" /></span>
Wanted to also fire the div like...:
onClick="toggle('feature');"
Can I chain onClick events to one click handler?
ie..
onclick="setCheckboxDisplay(this);toggle('feature');"
Or am I going round in circles.
Use event listeners. They're better anyway. :)
var check = document.getElementById('checkbox');
check.addEventListener('click', function () {
setCheckboxDisplay(this);
});
check.addEventListener('click', function () {
toggle('feature');
});
Ideally, you should try to start using unobstrusive javascript which basically means you separate the structure from function by moving your javascript inside a <script> tag or into a separate file. So your code would look like this and make it easier to read.
HTML
<span id="checkboxWrap" class="styledCheckboxWrap">
<input name="include" type="checkbox" id="checkbox" class="styledCheckbox" />
</span>
Script
<script>
$(function(){
$('.styledCheckbox').click(function(){
setCheckboxDisplay(this);
toggle('feature');
});
});
</script>
Yes, you can call multiple statements in the onclick attribute as long as they are semicolon-delimited. That gets unweildy though, so I'll usually define a new function to wrap the two into one call.
Just delegate this to a function that does all your work...
// Somewhere in the head of the file...
function doOnClickStuff(target) {
toggle('feature');
setCheckboxDisplay(target);
}
And then just have the onClick handler invoke that...
onClick="doOnClickStuff(target);"

Categories