execute a change event on input that was modified by another function - javascript

I have a function that does a calculation on an input, I have a function in another script I want to run when the value of the input changes.
I try to do with the change event but does not register the change unless you change the value myself.
$(document).ready(
function(){
$("#hello").val(1+1);
$("#hello").change( function(){
alert("change");
}
);
});
the solution I found was
$(document).ready(
function(){
$("#hello").val(1+1).trigger('change');
$("#hello").change( function(){
alert("change");
}
);} );

I think you should be attaching the event first & then make the change. Don't you?
Besides you might have to fire the event manually (using .trigger), like this:
$(document).ready(function(){
$(".hello").change( function(){ alert("change"); });
$(".hello").val(1+1).trigger("change");
});

Related

jQuery add event and instantly execute it

Often there is situation when I need to add some event with some customizations and then apply those customizations on page ready.
Usually I was doing it like:
$(window).resize(function(){
//some code
}).resize(); //trigger it when event defined
Problem with this solution is that if I have many resize events, then if I trigger it like this - it will re-execute all previously defined events too.
So another solution could be:
var myCallback = function(){ /*some code*/ };
$(window).resize(function(){
myCallback();
});
myCallback();
And it does it correctly but I find it not so good looking code and also there is no this inside function changed to event target DOM element that is very useful quite often.
Great would be something like
$(window).addEventAndFireOnce("resize", function(){});
such function is not so hard to implement, but I'm wondering if there is something like this there already in js or jQuery.
I don't know if I'm alone in this, but if I need to do that (and it's not uncommon) I bind a custom event name (possibly with a scope) at the same time as I bind the real event ("click" or "change" or whatever):
var myCallback = function(ev) { ... };
$(window).on("resize my-resize", myCallback).trigger("my-resize");
That's particularly useful when you're handling something like a "click" event on a checkbox. Triggering the "click" will actually update the checkbox "checked" state, which is not generally what you'd want to do. There's the jQuery .triggerHandler() method, but for whatever reason that only works on the first element in the jQuery object, so you can't trigger the handlers for all the checkboxes in a form with one call.
I would write it like so:
var myCallback = function(){ /*some code*/ };
$(window).resize( myCallback );
myCallback();
I think what you are looking for here is namespaced handlers
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).appendTo($log)
}
})();
$(window).resize(function() {
log('handler 1');
});
$(window).resize(function() {
log('handler 2');
});
$(window).on('resize.myspecial', function() {
log('handler 3');
}).trigger('resize.myspecial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="log"></div>

how to bind to both blur and change, but only trigger a function once in Jquery/Javascript?

I'm trying to trigger a function when a select element is changed.
Since Ipad is having trouble with on('change'), I also want to bind to 'blur', which works fine on Ipad.
However I don't want both events to trigger the function twice, so I need some kind of hook to make sure if both change and blur trigger, that the underlying function is only fired once.
This is what I'm doing now, but ... not very nice:
// make sure binding is only assigned once
var compSel = $('#my_select');
if ( compSel.jqmData('bound') != true ){
console.log("bound");
compSel.jqmData('bound', true)
.on( $.support.touch ? 'blur' : 'change', function(){
console.log("trigger");
// run function xyz
})
}
This works if you can live with all touchable devices making do with blur.
Question:
Does anyone have a better idea to make sure blur and change only trigger a function once?
Thanks for help!
Try creating a function, bound to both events, and adding a timeout to call the function. This way, if the function is called multiple times, it will only run once.
Something like this (you can adjust the timeout if needed):
function blurChange(e){
clearTimeout(blurChange.timeout);
blurChange.timeout = setTimeout(function(){
// Your event code goes here.
}, 100);
}
$('#my_select').on('blur change',blurChange);
don't know about ipad, but on browser maybe something like this
$("#dataTable tbody").on("click blur", "tr", function(event){
if (event.type == "click")
{
//do stuff
}
else
{
//do nothing
}
});
It's not nice, but you can call to change into the blur function, and do all the stuff in the change function:
...
$(document).on("change", "#yourelement", function(){
//do your stuff
});
....
$(document).on("blur", "#yourelement", function(){
$("#yourelement").change();
//alternatively, you can trigger the change event
//$("#yourelement").trigger("change");
});
It doesn't look nice, but I think it should work.
EDIT: If the browser launches both events (blur and change), this code will call twice the change functionality. I think that you can achieve that behavior with some kind of flag:
var executed = false;
...
$(document).on("change blur", "#yourelement", function(){
if(!executed){
executed = true;
//do your stuff
}
});
Attach multiple events you can use it like this also
<select class="form-control" id="Category" name="Category" required>
<option value="">Choose an option</option>
<option value="1">Your Text</option>
</select>
<p class=""></p>
$( "#Category" ).on( "blur change", function( event ) {
if($(this).val()===""){
$(this).next().text("Please choose category").css("color","#a94442");
}
else
{
$(this).next().text("");
}
});
In the case that both events are always triggered, we can set a flag for the first trigger and run the script. The second trigger will see the flag and clear it, and return so it only runs the first time.
In this case, you can blur multiple times without making a change, so it will only run every other time. If there is a change, then it should run for sure (whether the flag is on or off).
$(document).on("change blur",".selector", function(){
if($(this).data("triggered") == "1"){
$(this).data("triggered","0");
return;
}
$(this).data("triggered","1");
// your script here
// fix for "every other time" issue described above
var el = $(this);
setTimeout(function(){ el.data("triggered","0"); }, 200);
}
You might consider the "input" event, if you want to detect a change before the user leaves the element.
You might also consider writing the script so that it is safe to run multiple times (idempotent) and efficient enough that it doesn't affect performance if it runs twice.
You can bind to multiple events at the same time:
$(document).on('blur change','#mySelector',function(){
// this is called on either
});

How to check if there is already a click/event associated to an element

lets say I have
function trigger(){
$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});
So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click
How can i prevent this?
The problem is that you call $('a.pep').click() lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)
You should lever the DOM event bubbling model to handle this. jQuery helps you with the on method:
$(document.body).on('click', 'a.pep', function() {
console.log('element clicked');
$(document.body).append('<a class="pep">Click handlers handled automatically</a>');
});
See a working jsFiddle.
Note that I have removed the val call, because a elements can't have a value... Note also that the on method is introduced in jQuery 1.7; before that, use delegate:
$(document.body).delegate('a.pep', 'click', function() {
Small change to your trigger function is all you need. Just unbind the click event before binding to ensure that it is never added more than once. Also, you don't need to use each when binding events, it will add the event to each item automatically.
function trigger(){
$('a.pep').unbind('click').click(function() {
console.log($(this).val());
});
}
You can check using data('events') on any element if the required event is attached or not. For example to check if click event is attached or not try this.
if(!$('a.pep').data('events').click){
$('a.pep').click(function(){
console.log($(this).val());
});
}
you should use jQuery live here because you add DOM elements dynamicly and you want them to have the same click behaviour
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
$('a.pep').live('click', function(){
console.log($(this).val());
});
});
Try:
if($('a.pep').data('events').click) {
//do something
}
i think if you use live() event you dont need to make function
$('a.pep').live('click', function(){
console.log($(this).val());
});

jquery .bind prevent running on page load

I have a jquery function that binds a select field on a form to multiple actions. It binds to both change and keyup, so that mouse and keyboard clicks are both captured.
$(document).ready(function(){
$('#user_id').bind('change keyup',function () {
calculateAmounts();
}).change();
});
This works perfectly.
However, in addition to running on the change and keyup functions, the calculateAmounts() function is also called when first loading the page. I'd like to prevent this code from running when the page is first loaded.
You're triggering a change event when you call .change() on the $('#user_id') element, which will call your change/keyup event handler. If you remove the .change() call, then that event won't be triggered when the page loads:
$(document).ready(function(){
$('#user_id').bind('change keyup',function () {
calculateAmounts();
});
});
try this (taking in consederation that #user_id is input field)
$(document).ready(function(){
var yourVAL = $("#user_id").val();
$('#user_id').bind('change keyup',function () {
if($("#user_id").val() != yourVAL){
calculateAmounts();
}
}).change();
});

unload event when using master page

In my project i have used master page.In one particular page , i want a function to be executed on page unload(javascript event) event of that particular page.To achieve this i have written
$('body').bind('unload',function()
{
alert('hello');
} );
But this is not working.This function is not getting called when i move to other page.
How should i achieve this.
Well, I suppose its a problem when writing the question but your code should be:
$(window).bind('unload',function()
{
alert('hello');
});
You are missing the ending ); and the event should be bound to the window...
[Edit: Added the bind to the window instead of 'body']
$(window).bind("unload", function(){
alert(123);
});
worked for me :)
$(document).ready(function(){
$(window).unload( function () {
alert("Bye now!");
} );
});
try this. the document.ready function runs on pageload. so your bind will execute and is should work.

Categories