Why trigger and click do not work in this case? - javascript

I have a piece of code that does:
$('td.unique').live('click', function () {
//function logic here
});
This works fine on I click on the td of my table. All fine!
Now I would like to be able to have the same functionality programatically in certain cases without the user actually pressing click.
I have tried:
$(document).ready(function() {
$(".clearButton").click( function () {
var username = $(this).closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $(this).closest('tr').find('label').val();
var input = [];
input[0] = {action:'reset', id:user_id,user:username,};
$.ajax({
url: 'updateprofile.html',
data:{'user_options':JSON.stringify(input)},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
//all ok
console.log("ALL OK");
$(this).closest('tr').find('.unique').trigger('click');
$(this).closest('tr').find('td.unique').trigger('click');
$(this).closest('tr').find('td.unique').click();
}
else {
alert('failed');
}
}
});
This button is in the same row that the td.unique is
None of these work. Why? Am I doing it wrong? Is the function that I have bind in live not taken into account when I click this way?

You need to cache the $(this) inside the ajax function.
var $this = $(this);
the $(this) inside the ajax function will not refer to the element that is clicked
$(".clearButton").click(function () {
var $this = $(this);
var username = $this.closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $this.closest('tr').find('label').val();
var input = [];
input[0] = {
action: 'reset',
id: user_id,
user: username,
};
$.ajax({
url: 'updateprofile.html',
data: {
'user_options': JSON.stringify(input)
},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
console.log("ALL OK");
$this.closest('tr').find('.unique').trigger('click');
$this.closest('tr').find('td.unique').trigger('click');
$this.closest('tr').find('td.unique').click();
} else {
alert('failed');
}
}
});
});

Related

How to stop blur() event function to trigger twice?

I am trying to fetch the records from the database using blur function. There are two input fields where this function triggers. I have used different names, variables, javascript, controller using laravel to fetch the records. I am able to fetch the records through ajax and successfully opens the modal. When the modal pop ups when the blur function triggers, it also triggers the function for the second field.
I just want to trigger the modal according to the field, where the blur triggers and not to trigger twice.
//input field: originS
<script type="text/javascript">
$(document).ready(function(){
var origin = "";
var _token = "";
var ovalue = "";
$('#originS').blur(function(){
ovalue = "";
origin = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchOrigin') }}',
data:{origin:origin, _token:_token},
success: function(response){
if(response){
$("#originSelect").modal('show');
console.log(response);
$(".result").html(response);
$(document).on('change', '#selectSuburb', function () {
ovalue = $(this).val();
if ($(this).is(':checked')) {
$('#originS').val(ovalue);
$("#originSelect").modal('hide');
$this.die('blur');
}
});
$('#originSelect').on('hidden.bs.modal', function (e) {
if (ovalue == "") {
$("#originS").val('');
$(".result").html(response);
}
});
}
},
});
});
});
</script>
//input field: destS
</script>
<script type="text/javascript">
$(document).ready(function(){
var dest = "";
var _token = "";
var dvalue = "";
$('#destS').blur(function(){
dvalue = "";
dest = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchdest') }}',
data:{dest:dest, _token:_token},
success: function(response){
if(response){
$("#destSelect").modal('show');
console.log(response);
$(".dresult").html(response);
$(document).on('change', '#selectSuburbdest', function () {
dvalue = $(this).val();
if ($(this).is(':checked')) {
$('#destS').val(dvalue);
$("#destSelect").modal('hide');
$this.die('blur');
}
});
$('#destSelect').on('hidden.bs.modal', function (e) {
if (dvalue == "") {
$("#destS").val('');
$(".dresult").html(response);
}
});
}
},
});
});
});
</script>

get each column without using row.find('td:eq(0)')

How can I get each column in row without using .find('td:eq(0)')? I need another way to get each column.
$(document).on('click', '.delete_librarian', function()
{
var librarianDataRow=$(this).closest('tr');
var librarianId=parseInt(librarianDataRow.find('td:eq(0)').text());
var librarianName=librarianDataRow.find('td:eq(1)').text();
$('#confirm-model-body').text("Are you sure you want to delete "+librarianName+" data");
$('#confirm-modal').modal({backdrop: 'static'});
$('#confirm-model-yes-button').click(function () {
$.ajax({
url: "/api/admin/librarian",
type: "DELETE",
dataType: "json",
data: JSON.stringify({id:librarianId}),
success:function (data) {
if(data.success == true)
{
window.location.reload();
}
else
{
alert(data.message);
}
}
});
});
});
You could use vanilla JS instead if you don't want to use jQuery methods for whatever reason:
$(document).on('click', '.delete_librarian', function() {
var librarianDataRow = this.closest('tr');
var librarianId = Number(librarianDataRow.children[0].textContent);
var librarianName = librarianDataRow.children[1].textContent;
// ...
Could also use
$(document).on('click', '.delete_librarian', function() {
var librarianDataRow = this.closest('tr');
var librarianId = Number(librarianDataRow.cells[0].textContent);
var librarianName = librarianDataRow.cells[1].textContent;
// ...

Ajax calls going multiple times

I have written a code in Javascript in which I have attached an input type submit to a form. On form submit the listener gets called.
The problem is that on when I click the button once, one ajax call occurs. When I click it again two calls occur while only one call should occur on each click. Similarly on clicking 3 times 3 calls occur and so on...(the calls get increasing). If I refresh the page then the number gets reset. I have tried everything but I had no luck. If anyone found out what is wrong here it would be awesome. Thanks in advance.
javascript code:
$('input.create-discounts-quotations').click(function () {
var discount_quotation_type = $('input.quotation-discount-type').val();
if (discount_quotation_type == "value") {
var total = $('input.discount-input-quotation').val();
var discounted_price = product_price - total;
$('#final_discounted_amount').val(discounted_price);
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.quotation-response-discounts');
$(td).each(function () {
$(this).html(total);
});
});
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.product_final_price_discounted');
$(td).each(function () {
$(this).html(discounted_price);
});
});
var form1 = $('form#quotation_discount_update_form');
form1.on("submit", function (e) {
var form_data1 = form1.serialize();
$.ajax({
type: 'POST',
url: form1.attr('action'),
data: form_data1,
dataType: "json",
success: function (data) {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-success">Discount Added</div>');
}
});
e.preventDefault();
});
}
if (discount_quotation_type == "percentage") {
var total = $('input.discount-input-quotation').val();
var temp_first = product_price;
var temp1 = total / 100;
var temp2 = temp1 * product_price;
var discounted_price = product_price - temp2;
$('#final_discounted_amount').val(discounted_price);
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.quotation-response-discounts');
$(td).each(function () {
$(this).html(total);
});
});
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.product_final_price_discounted');
$(td).each(function () {
$(this).html(discounted_price);
});
});
var form1 = $('form#quotation_discount_update_form');
form1.on("submit", function (e) {
var form_data1 = form1.serialize();
$.ajax({
type: 'POST',
url: form1.attr('action'),
data: form_data1,
dataType: "json",
success: function (data) {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-success">Discount Added</div>');
}
});
e.preventDefault();
});
}
if (discount_quotation_type == "not_selected") {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-danger">Discount Method Not Selected</div>');
return false;
}
// return false;
});
That happen because every time you click your code will reattach the submit event so it will be duplicated in every click.
You should never attach the events inside other events, please put the submit event outside of the click event and the code should work, example :
var form1 = $('form#quotation_discount_update_form');
form1.on("submit", function (e) {
var form_data1 = form1.serialize();
$.ajax({
type: 'POST',
url: form1.attr('action'),
data: form_data1,
dataType: "json",
success: function (data) {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-success">Discount Added</div>');
}
});
e.preventDefault();
});
Else you have to remove the event handler every time using .off(), like :
form1.off("submit").on("submit", function (e) {

Jquery onchange Ajax

i made a function that sends data (ajax) to the database and depending on the response from the server i need to alert a message but it seems like whenvever i change the select option i get the alert message for each change(if i change the select four times when i click i get the alert four times ) , but if i remove my ajax function and replace it simply by an alert i get it once not repeating itself here is my JS
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
$(".red").on('click', function (evt) {
if ('done' == msg) {
evt.preventDefault();
alert('NOP');
}
})
});
});
the event that you are binding i think is wrong. For newly append items is better in your case to use
$(document).on('click', ".red", function (evt) {
})
And it must be moved outside the ajax success because now you are triggering it every time
----- Edited ---
If you want just to alert the output of the ajax you dont need the onClick event
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
if (msg === 'done') {
evt.preventDefault();
alert('NOP');
}
});
});
If you want to show the latest result on a button click you can store the msg on a global variable and on click of a div show that like
var globalMsg = "";
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
globalMsg = msg
});
});
$(".div").click(function() { alert(globalMSG); });

jQuery clearinterval / stopinterval doesn't work

I have an autorefresh function that gets called if a checkbox is checked and a button clicked. I want to stop the autorefresh when the checkbox is unclicked:
var refreshId = null;
$("#disINFRAlive").click(function(infralivefun) {
event.preventDefault(infralivefun);
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
if ($('#autorefcheck').is(':checked')) {
var refreshId = setInterval(function() {
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
}, 5000);
}
});
The autorefresh works if the checkbox #autorefcheck is checked and the button #disINFRAlive is clicked. However, I can't make it stop by unchecking the checkbox:
function stopinterval(){
clearInterval(refreshId);
return false;
}
$('#autorefcheck').click(function() {
stopinterval();
});
I tried to use clearInterval in various ways and none worked so far.
Remove the var keyword from the initialization of refreshId.
if ($('#autorefcheck').is(':checked')) {
refreshId = setInterval(function() {
The way you have it, you are redeclaring the variable in a different scope. That way, you cannot access it from stopInterval().

Categories

Resources