How remove function from this code after first usage this field? - javascript

$(document).ready(function(){
$('#id_laufzeit_bis').datepicker().on('changeDate', recalculate_deadline);
$('#id_kuendigungsfrist').change(recalculate_deadline);
$('#id_kuendigungsfrist_type').change(recalculate_deadline);
$('#id_kuendigung_moeglichbis').change(check_reminder_date);
$('#id_erinnerung_am').datepicker().one('hide', check_reminder_date);
});
How remove check_reminder_date function from this code after first usage this field? (#id_erinnerung_am)
$('#id_erinnerung_am').datepicker().one('hide', check_reminder_date);

I think this way:
$('#id_erinnerung_am').datepicker().one('click', check_reminder_date);
or might be this one:
$('#id_erinnerung_am').datepicker().end().one('click', check_reminder_date);
hide is not an event use click instead.

Edit Oh, this is what .one() should already do. It probably just didn't fire as one of the others already pointed out.
You can set a flag that indicates if the function has already been called previously.
var isFirstCall = false;
function check_reminder_date(){
if (isFirstCall) {
isFirstCall = false;
//do stuff
}
}

Use this trick to achieve what you want:
//caching the object with id #id_erinnerung_am
var id_erinnerung_am=$('#id_erinnerung_am');
//triggering an event on every close of the datepicker
id_erinnerung_am.datepicker({onClose:function(){
id_erinnerung_am.trigger('datePicker.hidden');
});
//binding the event once with the function 'check_reminder_date',
// this function will be executed only once
id_erinnerung_am.one('datePicker.hidden', check_reminder_date);

Related

addEventListener("touchstart") doesn’t work on phones [duplicate]

I don't know what I am doing wrong but here is an example of what I am doing and it doesn't seem to work.
someDom.addEventListener('mousemove',function(ev) {self.onInputMove(ev)},false);
someDom.removeEventListener('mousemove',self.onInputMove);
The removeEventListener code is executed but it just doesn't remove the 'mousemove' listener
removeEventListener removes the listener that exactly matches the function that was added.
In this case, the function that addEventListener added was:
var some_func = function(ev) {
self.onInputMove(ev);
};
Store a reference to the actual function and you'll be good. So for example, the following should work:
someDom.addEventListener('mousemove',self.onInputMove,false);
someDom.removeEventListener('mousemove',self.onInputMove,false);
onInputMove is not an event-callback method. So you need to do something like:
var event = function(ev) {self.onInputMove(ev)};
someDom.addEventListener('mousemove', event,false);
someDom.removeEventListener('mousemove', event, false);
Why make it yourself so hard, just use the following to bind an event to an element:
element.onmousemove = function(e) {
// Some code here...
alert("Mouse moved!");
};
Now, when you want to remove the event, just do this:
element.onmousemove = null;
Done!
Hope this helps you guys out!
This page comes first on searching this/such issue on Google. So apart from answers already mentioned, here is one more interesting fact for future:
Leaving out the third optional variable in addEventListener() for useCapture/useBubble (as it defaults to false) does create some issue while removing the same eventlistener with same callback name. I faced this issue while working on chrome. Cant say about other browsers.
So do mention the third variable explicitly as "false".

Get value from one click event to other event in JavaScript

I have code written by other like this.
<button onclick="javascript:confirm("Are you sure?");" id="confirm_button"/>
Now, to add more functionality to this button I am attaching one click event to the same button
$("#confirm_button").live("click",function(event){
//Need value from the confirm box.
//code goes here.
});
How to get the value from the first event in the event listener? I need if for my code to work.
The one way is that I have to move this confirm box into my click event listener, But requirements don't allow me.
Thanks
You can declare a global variable and the store value ion that,so it can be used in other functions
somewhat like this
<script>
//global variable here
var testvariable;
function1
{
//initalize value here
}
function2
{
//use here
}
</script>
Global Scope variables might help you with your problem. If a variable is declared outside a function, then that variable exists on the global object.
Check this link.you will get an pretty lot of information about the various scopes.. :)
<script>
var globalVariable= "someValue";//Use this variable anywhere u may need..
</script>
http://learn.jquery.com/javascript-101/scope/
Use confirm inside jquery Something like this:
$("#confirm_button").live("click",function(event){
var valid = confirm("Are you sure?");
if(valid){
//do something
var myVal = $("YOUR SELECTOR").val(); // to get the value of your selector.
}else{
// do something else
}
});
try this...
$("#confirm_button").live("click",function(event){
var isvalid = confirm("Are you sure?");
if(isvalid){
// to get the value of your selector.
}
else
{
// do something else
}
});
<input type="button" onclick="var tmp=confirm('Are you sure?');if(tmp) foo(); "
id="confirm_button" value="btn"/>
//and in javascript function write ur code
function foo()
{
alert('add functions');
}

callback after jQuery.trigger() function

i have got a little problem here. I have to trigger an event which contains $.post() to load a form and assign it to a DOM. After this is done, i have edit the fields of the form.
I tried:
$.when(function(){
$('#type_rank_field').trigger('change'); //calls the $.post() to load the form
})
.done(function(){
$('#quest_'+questions[i].split('|')[1]).children('option[value="'+questions[i].split('|')[0]+'"]').attr('selected',true);
});
Unfortunately this doesnt work and if i leave it just like that:
$('#type_rank_field').trigger('change');
$('#quest_'+questions[i].split('|')[1]).children('option[value="'+questions[i].split('|')[0]+'"]').attr('selected',true);
The change even looks like this:
$('#type_rank_field').live('change',function(){
var id = $(this).children('option:selected').attr('id');
var id_edited = get_id_from_id(id);
$.post('ajax/load_questions_of_rank.ajax.php',{id: id_edited},function(data){
//alert(data);
$('#rank_fields').html(data);
});
});
Then the form editation is executed before the form is properly loaded and attached to DOM. This might be a stupid question for JavaScript guys, but i am mainly a PHP guy so dont be cruel :-)
Thanks
Can separate out your change handler code? Something like this:
$('#type_rank_field').on('change',function(){
handleChange($(this));
});
function handleChange(elem, callback) {
var id = elem.children('option:selected').attr('id');
var id_edited = get_id_from_id(id);
$.post('ajax/load_questions_of_rank.ajax.php',{id: id_edited},function(data){
//alert(data);
$('#rank_fields').html(data);
if (typeof callback === "function") {
callback(data);
}
});
};
Then instead of triggering the change you can just call handleChange passing a callback to execute when the AJAX call is complete:
handleChange($("#type_rank_field"), function(data) {
$('#quest_'+questions[i].split('|')[1])
.children('option[value="'+questions[i].split('|')[0]+'"]')
.attr('selected',true);
});
Return the promise object from your event handler:
$(document).on('change','#type_rank_field',function(){
var id = $(this).children('option:selected').attr('id');
var id_edited = get_id_from_id(id);
return $.post('ajax/load_questions_of_rank.ajax.php',{id: id_edited},function(data){
//alert(data);
$('#rank_fields').html(data);
});
});
and then use triggerHandler() instead.
var promise = $('#type_rank_field').triggerHandler('change');
promise && promise.done(function(){
// do stuff
});
Here's a simple example showing the functionality being used: http://jsfiddle.net/WQPXt/
I think we have to add callback after posted
$('#type_rank_field').on('change', function(ev, cb){
var id = $(this).children('option:selected').attr('id');
var id_edited = get_id_from_id(id);
$.post('ajax/load_questions_of_rank.ajax.php',{id: id_edited},function(data){
//alert(data);
$('#rank_fields').html(data);
// add after callback to make sure that html is inserted
if(typeof cb == "function"){
cb.apply($(this)) // this apply with the jq object context or another context u want
}
});
the trigger change will look like this
$('#type_rank_field').trigger('change', [function(){
$('#quest_'+questions[i].split('|')[1]).children('option[value="'+questions[i].split('|')[0]+'"]').attr('selected',true);
}]);
.live has been deprecated in jQuery since v1.7, and has been removed in v1.9.
You should replace it with .on().
.on has 2 signatures for binding elements, whereas .live only had 1.
If the element exists at the time you are binding, you do it like this:
$('.element').on('click', function(){
.......
});
You can even use the shorthand:
$('.element').click(function(){
.........
});
If the element does not exist at the time, or new ones will be added (which is what .live was normally used for), you need to use "event delegation":
$(document).on('click', '.element', function(){
........
});
NOTE: You want to bind to the closest static element, not always document.
In the meantime, the jQuery Migrate plugin can be used to restore the .live() functionality if you upgrade your jQuery to the newest version.

jQuery - How to use e.preventDefault(); in a JavaScript function

I have this JavaScript function :
function putVote(trackid, vote) {
}
and I call this function trought :
Link
I would like to use e.preventDefault(); on putVote(), but I think I'm wrong in some ways. How can I do it?
Cheers
The simplest thing to do would be to return false from the function in the handler (return false would only work in putVote if the handler had return putVote('data1', 'data2)).
But as Pointy said, a much better technique is to attach the event handler from JavaScript, most easily achieved by using a library/framework such as jQuery or Prototype.
The easiest way:
Link
If you're using jQuery.
JS:
$("#link").click(function(evt) {
evt.preventDefault();
putVote('data1', 'data2');
});
HTML:
Link
If you're using the latest version of jQuery and the HTML5 doctype.
JS:
$("#link").click(function(evt) {
evt.preventDefault();
var $self = $(this);
putVote($self.data("one"), $self.data("two"));
});
HTML:
Link
In your case, the trick with using jQuery-style binding is that you want to be able to pass through element-specific parameters to the handler ("data1", "data2"). The "modern" way to do that would be this:
<a href="#" class='data-clickable' data-click-params='["data1", "data2"]'>Link</a>
Then, in a "ready" handler (or some other appropriate place), you'd bind your handler:
$('a.data-clickable').click(function(e) {
var elementData = $(this).data('click-params');
//
// ... handle the click ...
//
e.preventDefault();
});
The "elementData" variable will end up (in this case, anyway) being an array with two values in it, "data1" and "data2". You can give JSON-notation values to "data-foo" attributes, and when you fetch the attributes with the jQuery ".data()" method it will automatically decode the JSON for you.

Jquery if its the first time element is being clicked

I need my script to do something on the first time an element is clicked and continue to do something different on click 2,3,4 and so on
$('selector').click(function() {
//I would realy like this variable to be updated
var click = 0;
if (click === 0) {
do this
var click = 1;
} else {
do this
}
});//end click
really I think it should rely on the variables but I can't think of how to update the variable from here on out any help would be awesome.
Have a look at jQuery's .data() method. Consider your example:
$('selector').click(function() {
var $this = $(this),
clickNum = $this.data('clickNum');
if (!clickNum) clickNum = 1;
alert(clickNum);
$this.data('clickNum', ++clickNum);
});
See a working example here: http://jsfiddle.net/uaaft/
Use data to persist your state with the element.
In your click handler,
use
$(this).data('number_of_clicks')
to retrieve the value and
$(this).data('number_of_clicks',some_value)
to set it.
Note: $(this).data('number_of_clicks') will return false if it hasn't been set yet
Edit: fixed link
Another alternative might be to have two functions, and bind one using the one function in $(document).ready() (or wherever you are binding your handlers), and in that function, bind the second function to be run for all subsequent clicks using bind or click.
e.g.
function FirstTime(element) {
// do stuff the first time round here
$(element.target).click(AllOtherTimes);
}
function AllOtherTimes(element) {
// do stuff all subsequent times here
}
$(function() {
$('selector').one('click', FirstTime);
});
This is super easy in vanilla Js. This is using proper, different click handlers
const onNextTimes = function(e) {
// Do this after all but first click
};
node.addEventListener("click", function onFirstTime(e) {
node.addEventListener("click", onNextTimes);
}, {once : true});
Documentation, CanIUse
If you just need sequences of fixed behaviors, you can do this:
$('selector').toggle(function(){...}, function(){...}, function(){...},...);
Event handlers in the toggle method will be called orderly.
$('#foo').one('click', function() {
alert('This will be displayed only once.');
});
this would bind click event to Corresponding Html element once and unbind it automatically after first event rendering.
Or alternatively u could the following:
$("#foo").bind('click',function(){
// Some activity
$("#foo").unbind("click");
// bind it to some other event handler.
});

Categories