I have this jQuery code:
function action(action){
event.preventDefault();
var products = $("#check-list input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var string = JSON.stringify(products);
var table = $('#table').val();
if(products.length != '0' || action === 'old-all'){
$.ajax({
type: 'post',
url: 'app/toolbar.php',
data: {action:action, table:table, ids:string},
success:function(data){
localStorage.setItem('notify', data);
location.reload();
},
});
} else{
notify('You must choose an element first');
}
}
I'm using jQuery 3.3.1.
If i click a button without checking a checkbox i should get You must choose an element first but if i choose an element the toolbar.php should run and do the thing it has to be done(according to which button was pressed:
<button class="grey-btn" onClick="action('delete')">Delete</button>
<button class="grey-btn" onClick="action('update')">Update</button>
It works on Chrome perfectly but it doesn't work on Firefox. I was trying some answers that i found on some other similar 'works on chrome but not on firefox' questions but neither one of them worked :(
You do not define event so that is your problem. Get away from using inline event handlers and bind it with jQuery.
$("[data-action]").on("click", function (event) {
event.preventDefault();
var btn = $(this);
var action = btn.data("action");
console.log(action);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="grey-btn" data-action='delete'>Delete</button>
<button class="grey-btn" data-action='update'>Update</button>
If you really want to use inline event handlers than do
function action (event, method) {
event.preventDefault();
console.log(method);
}
<button class="grey-btn" onClick="action(event, 'delete')">Delete</button>
<button class="grey-btn" onClick="action(event, 'update')">Update</button>
Related
I'm trying to figure out how to change behaviour of a button using AJAX.
When the button is clicked, it means that user confirmed order recently created. AJAX calls /confirm-order/<id> and if the order has been confirmed, I want to change the button to redirect to /my-orders/ after next click on it. The problem is that it calls again the same JQuery function. I've tried already to remove class="confirm-button" attribute to avoid JQuery again but it does not work. What should I do?
It would be enough, if the button has been removed and replaced by text "Confirmed", but this.html() changes only inner html which is a text of the button.
$(document).ready(function () {
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
var id = this.value;
var url = '/confirm-order/'+id;
$.ajax({
type: 'get',
url: url,
success: function (data) {
$this.empty();
$this.attr('href','/my-orders/');
$this.parent().attr("action", "/my-orders/");
$this.html('Confirmed');
}
})
});
});
The event handler will be still attached to the button, so this will run again:
b.preventDefault();
which will prevent the default, which is opening the href. You need to remove the event handler on success. You use the jQuery #off() method:
$(".confirm-button").off('click');
or more shortly:
$this.off('click');
You can add to your success function something like: $this.data('isConfirmed', true);
And then in your click handler start by checking for it. If it's true, redirect the user to the next page.
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
if ($this.data('isConfirmed')) {
... redirect code ...
}
else {
... your regular code ...
}
}
You need to use .on() rather than .click() to catch events after the document is ready, because the "new" button appears later.
See http://api.jquery.com/on/
$(document).ready(function() {
$('.js-confirm').click(function(){
alert('Confirmed!');
$(this).off('click').removeClass('js-confirm').addClass('js-redirect').html('Redirect');
});
$(document).on('click', '.js-redirect', function(){
alert('Redirecting');
});
});
<button class="js-confirm">Confirm</button>
I am using http://datatables.net/
<button class='btn btn-success activeAccount'>Activate Account</button>
I trigger ajax call on onclick event, below is ajax call code:
$(".activeAccount").click(function() {
var intCounselorId = $(this).parent().parent().find('input[class="counselorId"]').attr("value");
var intOwnerId = $(this).parent().parent().find('input[class="userID"]').attr("value");
var strAction = 'activateAccount';
performAction(intCounselorId, intOwnerId, strAction);
});
function performAction(intCounselorId, intOwnerId, strAction) {
$.ajax({
url: '/admin/counselormanagement/expertmanagementgridaction',
data: 'intCounselorId='+intCounselorId+'&intOwnerId='+intOwnerId+'&strAction='+strAction,
type: "POST",
async:false,
success: function(intFlag) {
if(intFlag == 1){
location.reload();
}
}
});
}
I'm trying to run an onclick event which works normally on page one, but as soon as I go to page 2 (or any other) it stops working.
I'm using jquery-1.10.2.min.js and 1.9.4 version of datatable
Because the event is attached only to existing elements.
You should change it to:
$("#tableId").on("click", ".activeAccount", function(){
// your code goes here
});
Read more in the documentation of jQuery.on.
$(document).on("click",".activeAccount",function(e){
// your code goes here
});
I had the same issue. Every time my AJAX function(modalContentAjaxRefresh) update the table the paging stop. SO I just had to change my code from :
From :
$('.modal-toggle').off('click', modalContentAjaxRefresh).on('click',
modalContentAjaxRefresh);
to:
$('#DataTables_Table_0_wrapper').on("click", ".modal-toggle",
modalContentAjaxRefresh);
My button inside datatable is :
< a title="Edit" class="btn btn-xs btn-info modal-toggle"
data-style="zoom-in"
href="/setting/account/{{account_turn.uuid}}/update"
data-toggle="modal" data-target="#editAccount" wecare-method="GET">
As #squaleLis said, the event is attached to only existing elements.
So, in my case I defined onclick event for the button and called it.
<button class='btn btn-success activeAccount' onclick="YourMethod();">Activate Account</button>
function YourMethod() {
....same code..
}
$("#product-list").on("click",".btn-delete-product",function(e){
e.preventDefault();
var prodId = $(this).attr("product-id");
.... code to delete the record from the db...
});
product-list is the table where data gets loaded and has paging enabled.
This works perfectly for me.
I thinks a good and easy solution is to use drawCallback option
The main important thing is to reassign the elements when click the pagination.
//function to assign event
var assign_actions = function(){
//Some code
}
//when the page is ready
$( document ).ready(function() {
assign_actions();
//Code to assign event when paginate
$('.paginate_button').on('click', function(){
assign_actions();
});
});
I have an element which I bind more than one event handlers:
<div id="info">
<button class="action-delete" type="button">Delete</button>
</div>
$("#info").on("click", ".action-delete", function() {
$.event.trigger({
type: "application",
message: {
name: "item-delete",
item: $("#info").data("item")
}
});
});
Then I want the user to make sure before the delete operation is done, since there are so many elements with action-delete working for different models, so I tried to inject the following scripts to the page(from another js file):
$(document).on("click", ".action-delete", function(e) {
return confirm("Sure to delete?");
})
However I found that event the confirm window displayed, the delete operation is still completed before the user choose.
Any idea to fix it?
The problem is in your confirm call here:
$(document).on("click", ".action-delete", function(e) {
return confirm("Sure to delete?");
})
It should be something like this:
$(document).on("click", ".action-delete", function(e) {
e.preventDefault(); //prevent default behavior
var conf = confirm("Sure to delete?");
if(conf == true){
$("#info").trigger( "click" ); //trigger click event for delete
}
});
Plus I would recommend removing the click event from the parent div. Instead make a delete function and let the confirm dialog ('yes') trigger the function.
I have been all over Stack Overflow looking for a solution and none seem to work.
I cannot seem to figure out the issue. I have a button inside a <td> and on clicking it I want to make an AJAX call to update a database and upon success of that AJAX call I want to update the class of the <td> to mark the button as clicked.
I have tried var that = this; in the function. I've tried context: this, in the callback.
function setScoreA(event,candidate,rubric,category,score){
var author = document.getElementById("author").value;
if(author != ""){
$.ajax({
context: this,
type: "POST",
url: "stressBoardUpdate.php",
data: "candidate="+candidate+"&category="+category+"&score="+score+"&author="+author,
success: function(){
$(that).parent('td').siblings().removeClass('isScore');
$(that).parent('td').addClass('isScore');
}
});
}else{
alert("Author must contain something...");
}
}
Here is how the function would get invoked.
<input type="button" "="" value="5" onclick="setScoreA('Stress Board','Y235','Stress Board Rubric','Handled Stress','5');">
onclick="setScoreA does not set this to the element clicked but rather to window. The way you are using it. The way you are using it, I'm not sure that you could actually get a reference to the element. Instead of using onclick, you should bind an event listener (which you can do with jQuery anyway):
$("input").on("click", function () {
setScoreA(this, 'Stress Board','Y235','Stress Board Rubric','Handled Stress','5');
});
function setScoreA(element, ...
/* snip */
context: element
If you really wanted to stick with this for some reason, you could use:
setScoreA.call(this, 'Stress Board' ...
First of all, make use data attributes in your code and setup a common .click() listener
HTML:
<input type="button" class=".button-group" data-event="Stress Board" data-candidate="Y235" data-rubric="Stress Board Rubric" data-category="Handled Stress" data-score="5">
jQuery:
$(".button-group").click(function() {
// Do something
});
Also, I presume you are dynamically generating many buttons. The code above could be improved having only 1 click listener for the whole table, rather setting up a click listener for each item.
$("#wrapper").on("click", "input", function() {
var event = $(this).data("event");
var candidate = $(this).data("candidate");
var rubric = $(this).data("rubric");
var category = $(this).data("category");
var score = $(this).data("score");
setScoreA(this, event, candidate, rubric, category, score);
});
JSFIDDLE DEMO
Resources:
.data()
.click()
.on()
What's the best way to prevent a double-click on a link with jQuery?
I have a link that triggers an ajax call and when that ajax call returns it shows a message.
The problem is if I double-click, or click it twice before the ajax call returns, I wind up with two messages on the page when I really want just one.
I need like a disabled attribute on a button. But that doesn't work on links.
$('a').on('click', function(e){
e.preventDefault();
//do ajax call
});
You can use data- attributes, something like this:
$('a').on('click', function () {
var $this = $(this);
var alreadyClicked = $this.data('clicked');
if (alreadyClicked) {
return false;
}
$this.data('clicked', true);
$.ajax({
//some options
success: function (data) { //or complete
//stuff
$this.data('clicked', false);
}
})
});
I came with next simple jquery plugin:
(function($) {
$.fn.oneclick = function() {
$(this).one('click', function() {
$(this).click(function() { return false; });
});
};
// auto discover one-click elements
$(function() { $('[data-oneclick]').oneclick(); });
}(jQuery || Zepto));
// Then apply to selected elements
$('a.oneclick').oneclick();
Or just add custom data atribute in html:
<a data-oneclick href="/">One click</a>
You need async:false
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
$.ajax({
async: false,
success: function (data) {
//your message here
}
})
you can use a dummy class for this.
$('a#anchorID').bind('click',function(){
if($(this).hasClass('alreadyClicked')){
return false;
}else{
$(this).addClass('alreadyClicked);
$/ajax({
success: function(){$('a#anchorID').removeClass('alreadyClicked');},
error: function(){$('a#anchorID').removeClass('alreadyClicked');}
});
}});
Check this example. You can disable the button via CSS attribute after the first click (and remove this attribute after an ajax request or with a setTimeout) or use the jQuery.one() function to remove the trigger after the first click (without disabling the button)
var normal_button = $('#normal'),
one_button = $('#one'),
disabled_button = $('#disabled'),
result = $('#result');
normal_button.on('click', function () {
result.removeClass('hide').append(normal_button.html()+'<br/>');
});
one_button.one('click', function () {
result.removeClass('hide').append(one_button.html()+'<br/>');
});
disabled_button.on('click', function () {
disabled_button.attr('disabled', true);
setTimeout(function () {
result.removeClass('hide').append(disabled_button.html()+'<br/>');
}, 2000);
});
Although there are some good solutions offered, the method I ended up using was to just use a <button class="link"> that I can set the disabled attribute on.
Sometimes simplest solution is best.
You can disable click event on that link second time by using Jquery
$(this).unbind('click');
See this jsfiddle for reference
Demo
You can disable your links (for instance, href="#" ), and use a click event instead, binded to the link using the jQuery one() function.
Bind all the links with class "button" and try this:
$("a.button").click(function() { $(this).attr("disabled", "disabled"); });
$(document).click(function(evt) {
if ($(evt.target).is("a[disabled]"))
return false;
});