Two onclick event - javascript

I have onclick two times on same button, button for some the second one does not seem to work.
What do i need to do inorder to make both of them work.
<button type="submit" style="display:none;" id="done">Ok</button>
1st event
$(document).ready(function () {
$('#done').click(function () {
});
});
2nd event
$(function () {
$(document).on("click", "#done", Done);
});
function Done() {
$.ajax({
});
}

I believe you need to debug the issue a little bit. The title of the question indicates that javascript (or jQuery) is not handling the click event. This may not be the case.
$(document).ready(function () {
$('#done').click(function () {
console.log('first')
});
});
$(function () {
$(document).on("click", "#done", Done);
});
function Done() {
console.log('second')
}
<button type="submit" style="display:block;" id="done">Ok</button>
This runs fine, see the jsfiddle, the console in my browser logs both first and second messages. So it looks like both events are firing.
You now need to debug your ajax request or your controller. Try getting a simple file (single string within it) and alerting it. Then you can pinpoint your exact problem.

Check the Demo It works
Check the second demo it shows the defualt case ie when it works without error
Depending on the status of the request output is shown here the output is rejected hence enters the fail case
Jquery
$(document).ready(function () {
$('#show').click(function(){
$('#done').show();
});
$('#done').click(function () {
alert('called 1st');
$(this).siblings('.col-lg-11').attr('contenteditable', 'false');
$(this).siblings('.col-lg-11').attr('style', 'border:none;');
$(this).attr('style', 'display:none;');
$(this).siblings('.edit-link').attr('style', 'display:li;');
$(this).siblings('.cancel-link').attr('style', 'display:none;');
});
});
$(function () {
$(document).on("click", "#done", Done);
});
function Done() {
alert('called 2nd');
var s="sa";
var request = $.ajax({
type: "POST",
url: "http://www.google.co.in",
data: { name: "John", location: "Boston" }
}).done(function( ) {
alert( "Data Saved: " );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}

Related

javascript eventlistener not working for ajax loaded content

Hello I have loaded div via ajax and wanted to give javascript eventlistener with addEventListener method but this not working. Here below is my code
var QuantityMiniCart = function() {
var infor = document.querySelectorAll( '.mini-cart-product-infor' );
if ( ! infor.length ) {
return;
}
};
(function () {
document.addEventListener('DOMContentLoaded',function () {
QuantityMiniCart();
})
})();
infor.forEach(
function( ele, i ) {
input = ele.querySelector( 'input.qty' ),
}
// Check valid quantity.
input.addEventListener(
'change',
function() {
}
);
}
);
here is ajax code
$.ajax({
type: 'POST',
url: add_mini_cart_ajax.ajax_url,
data: {
action : 'mode_theme_update_mini_cart'
},
success: function( response ) {
$('.confirm-product').html(response);
},
error: function(e) {
console.log(e)
return;
}
});
The .confirm-product containing .mini-cart-product-infor which is loading from ajax. Please help for this
querySelectorAll can only select elements which exist at the time that command is run. It can't do anything which elements which don't exist yet!
So if you're loading more content via AJAX, after you've run the code shown in your question, then you'll need to separately add event listeners to any newly-downloaded elements, once the AJAX call is complete.

Ideas for mutiple ajax responds for remove loading flag in complete on click

I have this click handler which has an ajax call to get back some data and I set a flag in before send and clears it in complete. The problem that I am facing is that. When I tired to click this twice, the process goes like the following. I wondered what would be a better way to solve this issue. I thought about doing $.active to find out the numbers of ajax calls that's active but that doesn't seem like that right way
1 remove initiated, set flag,
2 remove initiated, set flag.
1 remove response completed, reload and clear the flag.
2 remove response completed, reload (Since the flag was clear by the 1 response, it adds the default which I don't want ).
$(document).on('click', '#remove', function () {
$.ajax({
type: 'POST',
url: '/remove'
data: {
fruits: $(this).val()
},
beforeSend: function () {
$('#fruit-table').addClass('loading');
},
success: function (data) {
loadFruitTable(data);
},
complete: function () {
$('#fruit-table').removeClass('loading');
}
};
loadFruitTable = function (data) {
$('#fruit-table').html(data);
if ($('.processing').length) {
preLoadDefault();
}
};
Just an idea: disable the remove button on click and enable it in the complete-part?
You could use .ajaxStart to show the loading object and .ajaxComplete to handle the event of all data being loaded:
$( document ).ajaxStart(function() {
$( ".log" ).text( "Triggered ajaxStart handler." );
});
$( document ).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
});
http://api.jquery.com/ajaxComplete/
$(document).on('click', '#remove', function () {
var $fruitTable = $('#fruit-table');
if ($fruitTable.hasClass('loading')) {
return;
}
$fruitTable.addClass('loading');
$.ajax({
type: 'POST',
url: '/remove'
data: {
fruits: $(this).val()
})
.then(loadFruitTable, function () {})
.then(reinitFruitTableStatus);
};
var reinitFruitTableStatus = function () {
$('#fruit-table').removeClass('loading');
};
loadFruitTable = function (data) {
$('#fruit-table').html(data);
if ($('.processing').length) {
preLoadDefault();
}
};
If the element #fruit-table is not dynamically created, you should store it once in a variable available in the whole code above.
Actually... Instead of adding a class, I added a count which increments in beforeSend and decrement in complete. So that way, i can always check if there is any process that's active.

Javascript onclick change button text for a few seconds

Trying to change the text on a button to processing for a few seconds when it is click
<div id="send"></div>
<button id="button">Send</button>
<script>
$(document).on("click", "#button", function() {
var Path = $('#send').html();
var success = function() { alert("Successful"); };
var error = function(message) { alert("Oopsie! " + message); };
</script>
You're close, you just need to do this $('#button').html("Processing");
Then in the success and error functions, you'll probably want to modify the button text to something else so that it no longer displays "Processing".
This is what you are probably looking for:
$(document).on("click", "#button", function() {
var defaultBtnValue = $('#send').html();
$('#send').html("Processing...");
$.ajax({
url: your_url,
type: "GET",
success: function() {
alert("Successful");
},
error: function(message) {
alert("Oopsie! " + message);
},
complete: function() {
$('#send').html(defaultBtnValue);
}
});
});
I'm assuming you wan't this "Processing" to show while something is.. well, processing, like doing an ajax call (this may be a setTimeout function as well). Good practice is to first save the default value of the button and make sure to reset it once an action is complete (succes or not) in case something goes wrong.

jQuery onclick event not working upon making multiple ajax requests

I am making few ajax requests in my jQuery file. On success of these jQuery requests, I wrote few on click events which are not working.
This is my code
$(document).ready(function (){
$.ajax ({
type: "POST",
url: 'myServlet',
async: false,
success: function (response) {
id = parseInt(response);
setOutputEvents();
}
});
function setOutputEvents() {
for (var queryNumber = 0; queryNumber <= id; queryNumber++) {
$.ajax({
type: "POST",
url: 'myOtherServlet',
data: {queryNumber: queryNumber},
success: success,
async: false
});
var success = function (response) {
//some code here
generateTable();
}
}
}
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
});
I understand making multiple ajax requests is a bad programming practice but what could be the reason for on click events not getting triggered?
These are the onclick events which are not working.
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
I am using Google Chrome Version 39.0.2171.95 on Windows 7.
Please do let me know if any further information is necessary.
Since you use ajax to load even the initial content it seems, .class / #me html elements likely do not exist on initial page load of the DOM. As you didn't post html, i'm guessing this is the case.
Thus, you need to use a delegated event click handler to respond to it
so, you would change
$("#me").on("click", function(){
to
$(document).on("click", "#me", function(){
and so forth to link it to the parent element that does exist, the document itself.
This would work:
$(".class").on("click", function(){
alert("me is triggered");
});
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").trigger("click");
}
Some notes:
Event handler must be registered before triggering click.
Triggered click selector must match the class which has the click event registered.
Functions must be defined before the usage.

jQuery: load response Document into div

I get an asyc response from the server that contains an HTML that I would like to display:
$( document ).ready( function ()
{
var options =
{
success: showResponse,
error: errorHandler,
type: 'post'
};
// bind to the form's submit event
$('#captureForm').submit(function()
{
$(this).ajaxSubmit(options);
return false;
});
});
function showResponse(responseDoc, statusText)
{
$('#output').html( responseDoc );
}
Where #output is a div where I would like the response document to be injected. The above code does not do the trick.
Any suggestions will be greatly appreciated.
Thanks.
-Raj
it might be a problem with options, try moving them into the function.

Categories