I have two pages with posts and reviews. The functions for the reply buttons are similar and both using unbind function in document ready event. Somehow, just one function will work even if they are accessing different classes. They both work when one is commented out. I appreciate any help and ideas. Thank you!
//Replies Posts
$(document).ready(function () {
$(document).unbind().on("click", ".btnReplySubmit", function() {
if (!$.trim($(this).closest(".myRepliesForm").find(".textareaReply").val())) {
alert("Empty Content");
}
else {
$.ajax({
url: "/Replies/Create/",
type: "post",
cache: false,
data: $(this).closest(".myRepliesForm").serialize(),
success: function() {
$(".reloadComments").load(location.href + " .reloadComments");
$(".reloadComments").show("slow");
}
});
$(this).closest(".myRepliesForm").find(".textareaReply").val("");
}
return false;
});
});
//Reply Review
$(document).ready(function () {
$(document).unbind().on("click", ".btnReplySubmitReview", function () {
if (!$.trim($(this).closest(".myRepliesFormReview").find(".textareaReplyReview").val())) {
alert("Empty Content");
}
else {
$.ajax({
url: "/ReviewReplies/Create/",
type: "post",
cache: false,
data: $(this).closest(".myRepliesFormReview").serialize(),
success: function () {
$(".reloadCommentsReview").load(location.href + " .reloadCommentsReview");
$(".reloadCommentsReview").show("slow");
}
});
$(this).closest(".myRepliesFormReview").find(".textareaReplyReview").val("");
}
return false;
});
});
Well if you use unbind on both event handlers, one of the functions is going to be inevitably unbound. You also do not need two ready calls as one is enough and finally, you can chain your event handler binding as follows :
$(document).ready(function () {
$(document).unbind()
.on("click", ".btnReplySubmit", function() {
if (!$.trim($(this).closest(".myRepliesForm").find(".textareaReply").val())) {
// ...
}
else {
// ...
}
return false;
})
.on("click", ".btnReplySubmitReview", function () {
if (!$.trim($(this).closest(".myRepliesFormReview").find(".textareaReplyReview").val())) {
// ...
}
else {
// ...
}
return false;
});
});
Because unbind will clear all previous bindings.
But.. why complicating things with bind/unbind on document, you could just do a click listener on both buttons :
$(document).ready(function () {
$('.btnReplySubmit').click(function(){
// alert(1);
});
$('.btnReplySubmitReview').click(function(){
// alert(2);
})
});
the main issue I see here is that you are unbinding events attached to $(document). also, according to jquery's api, you shouldn't be using unbind anymore as it is already deprecated.
instead, you should structure your code like so
$(document).ready(function() {
$('. btnReplySubmit').click(function() {
// your code here
})
$('. btnReplySubmitReview').click(function() {
// your code here
})
})
this makes your event declarations much clearer and much easier to read
All the answers are correct. I may just add that the selector in .on(events [, selector] [,data], handler) method is the event trigger, but event is bound to document in your case.
Related
i have this code with out the (doc on) it work in tell the div is reloaded after the reload the buttons do not work. With (doc on) the event fires but drops the variables any ideas?
$(document).on(".status").click(function (event) {
event.preventDefault();
var ids = $(this).attr("data-id-status");
var status = $(this).attr("data-status");
var record = this;
$(record).attr('class', 'btn btn-danger big-bnt prams');
$(record).prop('disabled', true);
$(record).html('Precessing');
$.ajax({
url: 'ajax.php',
type: 'post',
data: {action: 'status', id: ids, status: status},
success: function (data, status) {
alert(data);
if (data == '0') {
$('#flag-view').fadeOut(800, function () {
$("#r" + ids).remove();
$('#flag-view').fadeIn().delay(2000);
});
}
else if (data == '2') {
}
else if (data == '3') {
}
},
error: function (xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
})
Your declaration is incorrect change
From
$(document).on(".status").click(function (event) {
To
$(document).on("click", ".status", function(event){
});
That is not how .on() works.
.on() is a helper function that is used for adding event handlers to an element (with an optional selector), like so:
$(document).on("click", ".status", function (event) {
// Do your stuff here
});
Doing it like this (providing a selector) makes it into a delegated handler. Only one event handler is added to the document and any events that bubble up will be caught and given to the callback function.
You can also add the event handler directly to an element (or a collection of elements), like so:
$(document).find(".status").on("click", function (event) {
// ...
});
If the .status elements the handler was added to are removed then the handler will also be removed.
Event handling in jQuery can be a little confusing at first but it is quite logical. I would suggest that you read up on it to get a better sense of how it works.
I want to call a function every time my update was successful. The update is working my only concern is the alert pop-up every successful update.
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText)
{
popup();
}
}
});
var popup = function () {
$(document).ready (function(){
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
});
});
};
var popup = function () {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
On the first update, pop-up showed but it doesn't show on the 2nd update
I think it'll solve your issue
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText){
popup();
}
}
});
function popup() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
The $(document).ready jquery function waits until the DOM is loaded into your browser before it executes the javascript code contained within it's function scope {}.
So remove $(document).ready from your code.
Also note that single page applications only need to list $(document).ready once and all the listener events you setup are defined within it's body.
So you should have it listed somewhere at least once and then you define all your initial event listeners within its body.
I'm trying to rewrite some script. This script takes some data from data attributes and rebuild block with them. All was alright, but I need to do it via AJAX. Here my modified script:
(function($){
jQuery.fn.someItem = function()
{
var make = function() {
var _$this = $(this);
var $thumb = _$this.find('.thumb');
function init()
{
$thumb.on('click', function()
{
if (!$(this).hasClass('active')) setNewActiveItem($(this));
return false;
});
}
function setNewActiveItem($newItem)
{
$.ajax({
url: '/ajax-item?id=' + $newItem.data('id'),
type: 'GET',
success: function(response)
{
_$this.replaceWith(response);
**init();**
}
});
}
init();
};
return this.each(make);
};
})(jQuery);
All working fine, but after Ajax call and block replaced, I can't apply ajax-call in modified block again. I guess that I need to reinit "init()" function after "replaceWith()", but how to do it? Thank you for help.
You need to use a delegated event handler in the init() when attaching your click event to the .thumb elements. Try this:
var make = function() {
var _$this = $(this);
function init() {
_$this.on('click', '.thumb', function() {
if (!$(this).hasClass('active'))
setNewActiveItem($(this));
return false;
});
}
function setNewActiveItem($newItem) {
$.ajax({
url: '/ajax-item?id=' + $newItem.data('id'),
type: 'GET',
success: function(response) {
_$this.replaceWith(response);
}
});
}
init();
};
This works by assigning the click handler to the parent element and inspecting the click event as it bubbles up the DOM. It means that you can append any .thumb element at any time and not have to re-assign any new click handlers as the one defined on the parent will catch all.
I have the follwoing JQuery/AJAX code:
<script>
$('.warning-dialog').click(function () {
alert($(this).data("id"));
});
$(function () {
//twitter bootstrap script
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': $('.warning-dialog').data("id") },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
</script>
The first function gets the data-id of a button . The second function calls a PHP page and with the method GET should get the value from the first function.
I tried the code above but it didn't work.
My question is why and how can I fix it?
If these are two separate events, disconnected in time and you want to store the value from the first click and then use it in the second click, then you will have to store it somewhere. There are several options, the simplest being a variable.
$(function () {
var lastClickId;
$('.warning-dialog').click(function () {
lastClickId = $(this).data("id");
});
//twitter bootstrap script
// FIXME: you need to add logic here for what to do if lastClickId isn't set yet
// or create a default behavior in that case
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': lastClickId },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
Since it looks like you are requiring the first click to happen before the second click can have something to operate on, then you should probably either modify the UI to use different types of controls or you will need to add some error handling if the user doesn't click in the right order.
Actually it should have worked using $('.warning-dialog').data("id")
If your page contains only a single class warning-dialog, you approach will be worked. It seems you're referring this class to many elements.
$("#form").submit(function() {
$(this).ajaxSubmit({
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
});
return false;
});
When i click the submit button, This function works very good. But I would like to submit the form when a button is pressed. The above function is written in side
$(document).ready(function() {
But i want to write it inside a normal javascript function.
I am using the form plugin. form.min.js
Well, then subscribe to the click handler of your DOM element:
$(document).ready(function() {
$('#myButton').click(function() {
$("#form").ajaxSubmit(
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
);
return false;
});
});
try this
<form action='' method='post' onsubmit='return uploadimg();'>
<script>
function uploadimg(){
$(this).ajaxSubmit({
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
});
return false;
}
</script>
<button id="formSubmit">
binding the formsubmit to a buttons click event should work like this:
$('#formSubmit').on('click', function(){
$('#form').ajaxSubmit({
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
});
return false;
});
you almost got it all, the point in binding inside document.ready is thats the point where the dom is ready to be read and we know its safe to setup event handlers to the dom elements, the normal pratice is that inside youre docuement.ready handler you assign bindings to youre elements, asuming you have a button whith the ID of "submitImageForm" the code be lokking somthing like this
$(function(){
$("#submitImageForm").click(function(e){ // tell the browser we wanner handle the onClick event of this element
e.preventDefault() // this is to tell the browser that we are going to handle things and it shod not do its default (e.g sending the form up to the server and reloading)
$("#form").submit(function() {
$(this).ajaxSubmit({
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
})
})
})
})