I have this function below. It's a simple loop that look over a list of projects. For each project, it makes a NeDB query (does not matter here, just consider that it works as an Ajax function) that retrieve the tasks corresponding to the project and then display the tasks and an Edit button.
function myFunction() {
console.log('Work');
}
$.each(projects, function( index, project ) {
// tasks.find takes 100ms, it's like an Ajax request
tasks.find({}, function (err, tasklist) {
$('#my-list').append('<li>Edit</li>');
});
});
I would like that when I click on Edit, it runs myFunction().
So usually, I would have used on click like this :
function myFunction() {
console.log('Work');
}
$.each(projects, function( index, project ) {
// tasks.find takes 100ms, it's like an Ajax request
tasks.find({}, function (err, tasklist) {
$('#my-list').append('<li>Edit</li>');
$('#my-list li').on('click', function(){
myFunction();
}
});
});
The problem is that the on click function is in a loop, so it creates the function for each iteration of the loop, so it print 'Work' as many times as there are projects.
I also tried this
$('#my-list').append('<li onClick="myFunction()">Edit</li>');
But it does not recognize my function
What is the solution ?
We should only listen to click event of 1 <li> element
function myFunction() {
console.log('Work');
}
$.each(projects, function( index, project ) {
// tasks.find takes 100ms, it's like an Ajax request
tasks.find({}, function (err, tasklist) {
var $newLi = $('<li>Edit</li>');
$newLi.appendTo('#my-list');
$newLi.on('click', function(){
myFunction();
}
});
});
Hope that this can help :)
Change your on.click functionality to:
$("#my-list).on("click", function(e) {
// You can access the specific element child clicked
// by using $(e.target);
myFunction();
})
Related
I'm aware that this can be achieved via a Promise but I am struggling to figure out how.
jQuery('.parentDiv').on('click', '.link', function(e) {
jQuery.when(jQuery('.saveBtn').trigger('click', { 'evtData': 'link' })).then(function {
// rest of the logic that should be performed on click of .link
});
});
The click of .saveBtn calls a function named doAjax:
jQuery('.saveBtn').on('click', function() {
doAjax()
});
function doAjax() {
var ajaxCall = jQuery.ajax(ajaxObject);
ajaxCall.done(function(data, status, xhr) {
//some logic go here
});
return ajaxCall;
}
Despite this the logic inside the .then handler is getting executed first i.e before doAjax completes.
I believe I need to change the jQuery.when(jQuery('.saveBtn').trigger('click',{'evtData':'link'})) as it may not be getting the Promise state which it should and immediately getting marked as Resolved thereby executing the callback without waiting?.
I tried return doAjax in .saveBtn but that also did not make a difference.
Ideas please.
The issue is because trigger() is not an async function, so then is called immediately. It would make far more sense to just call doAjax() directly from the click of .link instead of faking DOM events. Try this:
jQuery(function($) {
$('.parentDiv').on('click', '.link', function(e) {
doAjax().then(function {
// rest of the logic that should be performed on click of .link
});
});
$('.saveBtn').on('click', function() {
doAjax()
});
function doAjax() {
var ajaxCall = $.ajax(ajaxObject);
ajaxCall.done(function(data, status, xhr) {
// some logic go here
});
return ajaxCall;
}
});
So I have a simple JQuery code:
$(function () {
var podatoci;
var i;
$(".front").on("load", init());
$("#remove").on("click", toggleRemove());
function init() {
load();
}
function load() {
$.get("data.json", function (data, status) {
podatoci = data;
fill();
})
}
function toggleRemove() {
console.log("Yes");
$(".likse-dislikes").toggle();
}
function fill() {
for (i = 0; i < podatoci.length; i++) {
$("#container").append("<div class='wrap'><img class='img' src='"+podatoci[i].url+"'/><div class='likes-dislikes'><img class='like' src='sources/like.png'/><img class='dislike' src='sources/dislike.png'/></div></div>");
}
}
});
When I click on the button with ID: remove it runs the toggleRemove() function.
However when I run the web page and when I got to to the console when I click on the button the function doesn't run, instead it does Console.log("OK") only once presumably when the page is loaded. Can anyone please explain where is the problem and how do I fix it?
Thank you in advance!
This doesn't do what you think it does:
$("#remove").on("click", toggleRemove());
This executes toggleRemove once, when the page loads, and sets the handler to the result of that function. (Which is undefined because the function doesn't return anything.)
You want to set the handler to the function itself, not the result of the function:
$("#remove").on("click", toggleRemove);
Additionally, if your element is being added to the page after this code executes (we don't know, though the code shown implies some dynamic elements being added) then you'd need to delegate the event:
$(document).on("click", "#remove", toggleRemove);
You spelled the class name incorrectly on your remove function.
$(".likse-dislikes").toggle();
Change it to
$(".likes-dislikes").toggle();
As I can see here $(".front").on("load", init()); $("#remove").on("click", toggleRemove()); you call your call back in time when you register event listener. Try this: $(".front").on("load", init); $("#remove").on("click", toggleRemove);
You could use $scope.apply(handler)
$scope.apply(function () {
// Angular is now aware that something might of changed
$scope.changeThisForMe = true;
});
I was trying to see if element enabled on the page before clicking on that. I want to create command that will check if element is enabled or not before clicking on it. I was going over API of nightwatch and still not sure how this commands works. I was trying following:
browserObj.elementIdEnabled(Cssselector, function (res) {
console.log(res);
});
But I think I should pass something else and not css selector into elementIdEnabled function. Ideally I want to chain 3 commands before clicking on element:
browserObj.perform(function () {
this.waitForElementPresent(cssSelector, timeout, function () {
this.waitForElementVisible(cssSelector, timeout, function () {
this.api.elementIdEnabled(cssSelector, function (res) {
browserObj.click(cssSelector, function (clickStatus) {
this.assert.equal(clickStatus.status, 0 );
});
})
})
});
});
module.exports.command = function (selector) {
this.waitForElementVisible(selector).click(selector);
return this;
};
By beatfactor from
https://github.com/nightwatchjs/nightwatch/issues/705
I'm super confused by my code. Let me show what it looks like:
$(document).ready(function ($) {
var customer_exists = false;
$.get(window.additional_parameters.customer_exists_url, "json")
.done(function () {
customer_exists = true;
})
.always(function () {
// Don't make request to buy clickable until we know if the customer exists
$('#request-to-buy').on('click', function(e) {
request_to_buy(customer_exists);
});
});
function request_to_buy(customer_exists) {
response = can_request_to_buy();
response.done(function (response) {
if (customer_exists) {
// Actually create the request on the server
$.post(window.additional_parameters.request_to_buy_url,
{'ticket_id': window.additional_parameters.ticket_id},
"json")
.done(function (response) {
request_to_buy_success(response);
})
.fail(function () {
var message = handle_ajax_response(response);
show_ajax_message(message);
});
} else {
show_pre_stripe_popup();
}
})
.fail(function (response) {
var error_message = handle_ajax_response(response);
show_ajax_message(error_message, 'danger');
});
}
$(document).ready(), we set a variable called customer_exists. This variable guides the path of the code afterwards and is pretty important. If the $.get AJAX request is successful, it's true, otherwise it remains it default value of false. After the AJAX response, we attach a click event to "#request-to-buy." My goal here is to create a closure and pass in the value of customer_exists that was just set. This doesn't happen.
A good portion of the time ( I had it work correctly once or twice ), when I inspect request_to_buy in the debugger, I can see that customer_exists is a jQuery click event. why ??? Shouldn't it take on the value of the customer_exists from the surrounding scope of where the function was created? Can anyone explain what is going on here?
Thank you
EDIT: Here's a little more information that describes how it works sometimes...
The first time that I click '#request-to-buy', the handler is
function(e) {
request_to_buy(customer_exists);
}
This is what we would expect. e contains the click event, customer_exists retains it's value, and everything works inside request_to_buy.
Every time I click '#request-to-buy' after the first, instead of the above function being called, request_to_buy is called directly, and instead of passing in customer_exists in the first parameter, the click event is passed in instead. I hope this helps someone.
You should be able to do this without the need for the cumbersome outer var customer_exists.
For example :
$(document).ready(function ($) {
$.get(window.additional_parameters.customer_exists_url, "json").then(function () {
// Don't make request to buy clickable until we know if the customer exists
$('#request-to-buy').on('click', request_to_buy);
}, function() {
$('#request-to-buy').on('click', show_pre_stripe_popup);
});
function request_to_buy(e) {
e.preventDefault();
can_request_to_buy().then(function(response) {
// Actually create the request on the server
$.post(window.additional_parameters.request_to_buy_url, {
'ticket_id': window.additional_parameters.ticket_id
}, "json").then(request_to_buy_success, function() {
show_ajax_message(handle_ajax_response(response));
});
}).fail(function(response) {
show_ajax_message(handle_ajax_response(response), 'danger');
});
}
}
show_pre_stripe_popup will also be passed an event and you may need to do e.preventDefault(); there too.
You will need to check that the correct parameters are passed to the various error handlers. I can't verify them.
If it still doesn't work, then you must suspect other code that's not included in the question, for example the function can_request_to_buy().
var customer_exists = false;
Declare this outside of ready block.
I'm sure this is very simple, but I can't seem to find the answer.
I have a RoR app, and in my application.js file I want to call a function from within a function.
application.js:
jQuery(function_1($) {
$("#select_box").change(function() { ....
....
function_2 ();
return false;
});
jQuery(function_2 () {
...
return false;
);
function 1 is triggered when a select box is changed and works correctly. The issue is that function 2 is executed as soon as a new page is loaded. I only want function 2 to be called from within function 1.
How can I do that?
The problem is that when you put code inside of a block like this:
jQuery(function() {
$("#select_box").change(function() {
function_2();
return false;
});
});
The code is automatically executed. This is equivalent to
$(function() {
});
or
$(document).ready(function() {
});
Which should give you an idea of why function_2 is being invoked on page load. To remedy this, just define the function like this:
jQuery(function() {
var function_2 = function() {
return false;
};
$("#select_box").change(function() {
function_2();
return false;
});
});
See jQuery docs: http://learn.jquery.com/using-jquery-core/document-ready/
If you're using the asset pipeline, you shouldn't have javascript functions in application.js at all, it should just be a manifest. So, assuming you've disabled the asset pipeline, I think you just need to change how you define function_2. Try this:
var function_2 = function () {
...
return false;
};
$("#select_box").change(function() {
....
function_2 ();
return false;
});
function function_2 () {
...
return false;
}
Your question says:
function 1 is triggered when a select box is changed and works correctly. The issue is that function 2 is executed as soon as a new page is loaded. I only want function 2 to be called from within function 1.
$(document).on("change","#select_box",function(e) {
// used on function to incorporate for turbolinks
// your code
// to trigger your function1 when select box is changed
function1 ();
e.preventDefault();
});
function function1(){
//your code
// to trigger your function2 inside function1
function2();
}
function function2(){
//your code
}