I have this switch below:
<input id="upperLightSwitch" type="checkbox" checked data-size="mini">
With this, switchChange (on change) event in the $(document).ready triggers fine when the switch state is changed by clicking on it.
$('#upperLightSwitch').on('switchChange.bootstrapSwitch', function (event, state) {
sendStateToArduino("upperLight");
updateLightState("upperLight",state);
});
My problem is when I check a value from the database and it is 0. I am setting the toggle switch state to false and setting the 3rd parameter to false which says to not fire the event on change, but the event still triggers as both methods in the event above are being executed.
Quote from Bootsrap website:
$('#toggle-state-switch').bootstrapSwitch('state', false, false); // Set the state as off and do not trigger switchChange event
The one I am using
$('#upperLightSwitch').bootstrapSwitch('state', false,false );
Before the code of the event, I am calling a method to check that value with the database when everything loads.
What am I missing?
EDIT: Bootstrap switch link
The last parameter should be true not false, like below to disable the event from triggering
$('#upperLightSwitch').bootstrapSwitch('state', false,true );
You can't do it with "out of the box" javascript (methods), but there is a pretty simple work around!
Here's what I did... (which works great!)
In your document ready
$(document).ready(function () {
//declare a flag.
$.onC = 0;
Then when you're setting the Toggle/Switch...
function yourFunction()
{
//first set the flag.
$.onC = 1;
$(th).bootstrapToggle('off');
}
Now in the change function...
$(".onOff").on("change", function (e) {
//check the flag and reset it
if ($.onC == 1)
{
$.onC = 0;
return;
}
Related
The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse. Why is this?
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<script>
$(function() {
$(":input#single").change(function() {
/* Logic here does not execute when val() is used */
});
});
$("#single").val("Single2");
</script>
Because the change event requires an actual browser event initiated by the user instead of via javascript code.
Do this instead:
$("#single").val("Single2").trigger('change');
or
$("#single").val("Single2").change();
I believe you can manually trigger the change event with trigger():
$("#single").val("Single2").trigger('change');
Though why it doesn't fire automatically, I have no idea.
Adding this piece of code after the val() seems to work:
$(":input#single").trigger('change');
As far as I can read in API's. The event is only fired when the user clicks on an option.
http://api.jquery.com/change/
For select boxes, checkboxes, and
radio buttons, the event is fired
immediately when the user makes a
selection with the mouse, but for the
other element types the event is
deferred until the element loses
focus.
To make it easier, add a custom function and call it whenever you want to change the value and also trigger a change:
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTrigger("NewValue");
Or you can override the val() function to always call the change when val() is called:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
In case you don't want to mix up with default change event you can provide your custom event
$('input.test').on('value_changed', function(e){
console.log('value changed to '+$(this).val());
});
to trigger the event on value set, you can do
$('input.test').val('I am a new value').trigger('value_changed');
If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:
window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);
I ran into the same issue while using CMB2 with Wordpress and wanted to hook into the change event of a file upload metabox.
So in case you're not able to modify the code that invokes the change (in this case the CMB2 script), use the code below.
The trigger is being invoked AFTER the value is set, otherwise your change eventHandler will work, but the value will be the previous one, not the one being set.
Here's the code i use:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
if (arguments.length >= 1) {
// setter invoked, do processing
return originalVal.call(this, value).trigger('change');
}
//getter invoked do processing
return originalVal.call(this);
};
})(jQuery);
$(":input#single").trigger('change');
This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this
$('#machineMake').val('<?php echo $_GET['headMake']; ?>').trigger('change');
And the first event worked.
To change the value
$("#single").val("Single2");
Also to trigger a change event
$("#single").val("Single2").change();
this logic is instrumental when multiple select options are on a page.
one changes and other select options have to change but do not trigger a change event.
I have a button similar to below
<button id="uniqueId" onclick="runMethod(this)">Submit</button>
What I'm trying to do is stop the runMethod from running, until after I've done a check of my own. I've tried using the stopImmediatePropagation function, but this doesn't seem to have worked. Here's my jQuery:
$j(document).on('click', '#uniqueId', function(event) {
event.stopImmediatePropagation();
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Note: runMethod basically validates the form, then triggers a submit.
What you want to do, especially in the way that you want to do it, requires a some sort of workaround that will always be a bit fiddly. It is a better idea to change the way the button behaves (e.g. handle the whole of the click event on the inside of the jQuery click() function or something along those lines). However I have found sort of a solution for your problem, based on the assumption that your user will first hover over the button. I am sure you can extend that functionality to the keyboard's Tab event, but maybe it will not work perfectly for mobile devices' touch input. So, bear in mind the following solution is a semi-complete workaround for your problem:
$(document).ready(function(){
var methodToRun = "runMethod(this)"; // Store the value of the onclick attribute of your button.
var condition = false; // Suppose it is enabled at first.
$('#uniqueId').attr('onclick',null);
$('#uniqueId').hover(function(){
// Check your stuff here
condition = !condition; // This will change to both true and false as your hover in and out of the button.
console.log(condition); // Log the condition's value.
if(condition == true){
$('#uniqueId').attr('onclick',methodToRun); // Enable the button's event before the click.
}
},
function(){
console.log('inactive'); // When you stop hovering over the button, it will log this.
$('#uniqueId').attr('onclick',null); // Disable the on click event.
});
});
What this does is it uses the hover event to trigger your checking logic and when the user finally clicks on the button, the button is enabled if the logic was correct, otherwise it does not do anything. Try it live on this fiddle.
P.S.: Convert $ to $j as necessary to adapt this.
P.S.2: Use the Javascript console to check how the fiddle works as it will not change anything on the page by itself.
Your problem is the submit event, just make :
$('form').on('submit', function(e) {
e.preventDefault();
});
and it works. Don't bind the button click, only the submit form. By this way, you prevent to submit the form and the button needs to be type button:
<button type="button" .....>Submit</button>
Assuming there's a form that is submitted when button is clicked.
Try adding
event.cancelBubble();
Hence your code becomes:
$j(document).on('click', '#uniqueId', function(event) {
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Your code is mostly correct but you need to remove J:
$(document).on('click', '#uniqueId', function(event) {...
You also need to remove the onClick event from the inline code - there's no need to have it there when you're assigning it via jQuery.
<button id="uniqueId">Submit</button>
Is there some way to run a function when a input is disabled/enabled from another part of the code, for example when this code is run:
$('#myinput').prop('disabled', true);
I want another part of the code to be notified about this, but without making it dependent on the other part. Something similar to how "change" event works. But there's no "disabled" event...
You can call notification trigger in the next line with an if statement
document.getElementById("email").disabled=true;
if(document.getElementById("email").disabled == true)
{
alert("Notifying..");
//call the trigger function
}
There is no event that will trigger when those properties are changed.
You can do this some other way.
Set hidden field for this enable disabled value like 1 / 0
$("#hiddenid").trigger("hiddenidchange");
$("#hiddenid").on("hiddenidchange", function () {
});
refer How do I trigger an onChange event for a hidden field?
I've got a 'catch 22' in Chrome. I cannot programmatically select a radio button within a click event if any other function bound to the same event makes a call to preventDefault().
For example, I have a radio button with a parent element bound to a click event in which preventDefault() is called. If the radio button is clicked directly it is not checked. This is to be expected. However, I actually need the radio button to be selected so within code I attempt to check it in another function bound to the click event: $(this).prop('checked', true);.
Oddly, this doesn't work and I cannot remove the call to preventDefault() or disable propagation because it is in third party code that I need to run.
Is this a bug? Any suggested workarounds?
Here is an example:
http://jsfiddle.net/LnLuk4st/
UPDATE:
I have tried #RGraham's suggestion. His example clearly works, but oddly it does not work in the context of my code. #RGraham's code had a syntax error which made it appear to be working.
Here's some context:
// Remember kendo tab
$(".k-tabstrip").each(function () {
var $tabStrip = $(this);
var $tabs = $tabStrip.find(".k-tabstrip-items .k-item");
var tabCookie = "Current_Tab_" + $tabStrip.attr("id");
// On tab change, set cookie
$tabs.click(function () {
createCookie(tabCookie, $(this).attr("aria-controls"), 1);
$tabStrip.parent().css({ 'min-height': $tabStrip.parent().height() });
if ($(this).is('input')) { // Doesn't eval to true, 'this' is always a '.k-item'.
$(this).prop("checked", true);
} else {
// Never works if the input is clicked directly
$(this).find('input').prop("checked", true);
}
});
// #RGraham's suggestion...
$tabs.on('click', 'input', function() {
$(this).prop("checked", true); // Line reached but doesn't work either :(
});
// If cookie set, select tab
var tab = readCookie(tabCookie);
if (tab) {
$tabs.each(function () {
if ($(this).attr("aria-controls") == tab) {
$(this).click();
}
});
}
});
I still believe this behaviour to be a bug but I have found a workaround.
Capture the click of the radio button directly, prevent propagation, then programmatically click the parent of the radio button. This allows the third party code to run without applying preventDefault to the radio button.
// preventDefault bug fix.
$tabs.find("input").click(function (e) {
e.stopPropagation();
$(this).parent().click();
});
code:
https://dl.dropboxusercontent.com/u/16952797/webdev/uppg1/kontakt.html
http://jsfiddle.net/v8uMJ/ (the result box does not succesfully render the page or reproduce the bug)
relevant code:
function addEvent(element, eventType, theFunction, capture)
{
if(element.addEventListener)
{
element.addEventListener(eventType, theFunction, capture);
}
else if(element.attachEvent)
{
element.attachEvent( "on" + eventType, theFunction);
}
}
function removeDefaultOption(event)
{
document.getElementById("selectSuggestion").options[0].style.display = "none"; // <-- looks awkward
//document.getElementById("selectSuggestion").remove(0); // <-- also looks awkward and needs boundaries so that all options don't get removed after each click
//delay(1000); // <-- tried delaying the thread but it didn't work..
//setInterval(function(){},1000); // <-- tried delaying the thread but it didn't work..
}
function addEventListeners()
{
...
addEvent(document.getElementById("selectSuggestion"), "click", removeDefaultOption, false);
}
context: So what I'm trying to do is whenever you click on the select element in the suggestion form (swe: Förslag) I want the first option (value: --Välj Förslag--) to disappear from the list. The problem is that the options are displayed "too fast" so I either need to a) delay the displaying of the options after setting the style.display of the first option or b) I need to prevent the default event of clicking on select and then override it with my own function so I can control when it should be run (I don't know the name of the native function that is run when you click on the select element).
Use the "focus" event instead of the "click" event. This fires the function direclty when it's in focus instead of "waiting" for the click to be completed.
Cleaned JS-fiddle: http://jsfiddle.net/vhS3p/1/
document.getElementById("selectSuggestion").addEventListener("focus", removeDefaultOption, false);
Try removing the option you want like so:
var index = 0;
var select = document.getElementById("selectSuggestion");
select.removeChild(select[index]);