I have an HTML table which uses jQuery DataTables (https://datatables.net/). The rows are rendered with html links to delete a row. I have used the following code to handle the click event of link, delete the row on the server and then animate deletion of the row on the front end.
$(document).on("click", ".delete-operation", function (e) {
e.preventDefault();
var oTable = $('#alloperations').dataTable();
var operationId = $(this).data('id');
// Get the parent table row and mark it as having been selected
// due to the fact rowindex does not work in order in datatables
var tableRow = $(e.toElement).parents('tr').addClass('row_selected');
bootbox.confirm("Are you sure?", function (answer) {
if (answer) {
// send request to delete operation with given id.
$.ajax({
type: 'delete',
url: "/operations/" + operationId,
success: function () {
var anSelected = fnGetSelected(oTable);
//Get all the row cells and animate a deletion
tableRow.children().animate({ backgroundColor: "red", color: "black" }, 300, function() {
tableRow.fadeOut(2000, function() {
oTable.fnDeleteRow(anSelected[0]);
});
});
},
error: function(result) {
$("#messageContainer").html(result.responseJSON.ResponseView);
}
});
return true;
}
else {
// User clicked cancel
return true;
}
});
});
QUESTION: This works perfectly in Chrome but does not work at all in Firefox, does anyone know how I would get it to work in Firefox as well?
You should use the cross browser property 'target' of event object:
var tableRow = $(e.target).parents('tr').addClass('row_selected');
Related
In one page I have three connected dropboxes with parent child relation in this order
Company->Analysis->Scenario
I also have the pair or Node dropboxes in a html table which should be repeated in each row. These dropboxes values should be changed as the parent Scenario dropbox combo value changes.
I also want them to show the relevant value as selected for each row.
This maybe straightforward for a frontend developer but I am struggling a lot.
The top dropboxes are nearly ok. For the dropboxes from the table I managed to change the first row at one point but now lost that version :(
Can you please help me to solve this. I tried nearly everything?
Kind Regards,
Sofia
enter image description here
This is the related code part
`<script charset="utf-8" type="text/javascript">
function _updateNodes() {
var source_elms = document.querySelectorAll("[id='source1']");
for(var i = 0; i < source_elms.length; i++){
source_elms[i].setAttribute('disabled', 'disabled');
if (source_elms[i].hasChildNodes()) {
source_elms[i].empty();
}
for (node in allowed_nodes){
if node[0]==edge.source_id and node[2]== scenario_id
source_elms[i].append($('<OPTION value = node[0] selected>node[1]</option>');
endif
if node[0]!=edge.source_id and node[2]== scenario_id
source_elms[i].append($('<OPTION value = node[0]>node[1]</option>');
endif;
}
}
}
// jQuery selection for the 2 select boxes
var dropdown = {
company: $('#company'),
analysis: $('#analysis'),
scenario: $('#scenario'),
source: $('#source1'),
target: $('#target1')
};
// function to call XHR and update analysis dropdown
function updateAnalysiss() {
var send = {
company_id: dropdown.company.val()
};
dropdown.analysis.attr('disabled', 'disabled');
dropdown.scenario.attr('disabled', 'disabled');
dropdown.analysis.empty();
dropdown.scenario.empty();
$.getJSON("{{ url_for('_get_analysiss') }}", send, function(data) {
data.forEach(function(item) {
dropdown.analysis.append(
$('<option>', {
value: item[0],
text: item[1]
})
);
});
dropdown.analysis.removeAttr('disabled');
dropdown.scenario.removeAttr('disabled');
updateScenarios();
_updateNodes();
});
}
function updateScenarios() {
var send = {
analysis_id: dropdown.analysis.val()
};
dropdown.scenario.attr('disabled', 'disabled');
dropdown.scenario.empty();
$.getJSON("{{ url_for('_get_scenarios') }}", send, function(data) {
data.forEach(function(item) {
dropdown.scenario.append(
$('<option>', {
value: item[0],
text: item[1]
})
);
});
dropdown.scenario.removeAttr('disabled');
});
}
var scenario_id = Null;
function updateNodes() {
scenario_id: dropdown.scenario.val()
}
// event listener to company dropdown change
dropdown.company.on('change', function() {
updateAnalysiss();
});
// event listener to analysis dropdown change
dropdown.analysis.on('change', function() {
updateScenarios();
});
// event listener to scenario dropdown change
dropdown.scenario.on('change', function() {
alert("aa");
_updateNodes();
alert("bb");
});
$('#company').change(function() {
updateAnalysiss();
});
$('#analysis').change(function() {
updateScenarios();
});
$('#scenario').change(function() {
alert("aa1");
_updateNodes();
alert("bb1");
});
// call to update on load
updateAnalysiss();
</script>
`
On a page with a tab control, each tab contains a table, each tr contains a td with a button which has a value assigned to it.
<td>
<button type="button" class="btn" name="deleteEventBtn" value="1">Delete</button>
</td>
This code below works for the first delete. After the AJAX call & the refresh of the div, no further delete buttons can be clicked. The .on is attached to the document. The same happens if I attach it to the body or anything closer to the buttons.
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
}
});
}
$(document).ready(function () {
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
}
});
});
Any ideas? Could it be related to the wildcard for starts with [name^="delete"]? There are no other elements where the name starts with 'delete'.
EDIT
When replacing
$(container).trigger('refresh');
with
location.reload();
it "works", however that refreshes the whole page, loses the users position and defeats the point of using AJAX.
As the button click is firing at first attempt, there is no issue in that code. All you have to do is, put the button click event in a method and call it after the refresh. This way, the events will be attached to the element again. See the code below,
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
BindEvents();
}
});
}
$(document).ready(function () {
BindEvents();
});
function BindEvents()
{
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
});
}
Apologies to all and thanks for your answers. The problem was due to the way the popup was being shown & hidden.
$('#delete-popup').modal('show');
and
$('#delete-popup').hide();
When I changed this line to:
$('#delete-popup').modal('hide');
it worked. Thanks to LShetty, the alert (in the right place) did help!
If you are using Bootstrap Modal
After Ajax Request before Refreshing page add
$('.modal').modal('hide');
This Line will Close your Modal and reload your page. Before that it will complete all Ajax Request things.
But for google chrome there is no issues :) hope this help someone.
I have an ASP.NET website which uses jQuery 1.8.2. I have a dialog box which lists UserReporting Settings from a DB whether a column is displayed or not. The User can change this by clicking the change columns buttons which open the dialog box - there are then a list of Available Columns and Current Columns and the User can drag and drop from one side to the other.
The code in the Update button off the dialog button is what is not working - the 'Hello' alert fires but if I set a breakpoint in my ashx Handler it never gets hit?
$("#UserReportSettings").dialog({
resizable: false,
autoOpen: false,
height: 600,
width: 525,
modal: true,
buttons: {
"Update Columns": function () {
var columns = [];
$('#currentColumnsList').each(function () {
// this is inner scope, in reference to the .phrase element
var column = '';
$(this).find('li').each(function () {
// cache jquery var
var current = $(this);
// check if our current li has children (sub elements)
// if it does, skip it
// ps, you can work with this by seeing if the first child
// is a UL with blank inside and odd your custom BLANK text
if (current.children().size() > 0) {
return true;
}
// add current text to our current phrase
column += (current.text() + ',');
});
// now that our current phrase is completely build we add it to our outer array
columns.push(column);
});
$.ajax({
type: 'POST',
url: '/MyWebsite/Handlers/UpdateUserReportingSettings.ashx',
data: { reportingSettings: columns.join() },
beforeSend: function (xhr, opts) {
},
success: function (data) {
alert("Hello");
window.top.location.href = "landing.aspx";
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error' + xhr.responseText);
}
});
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
EDIT - Following Archers comment
If I paste localhost/Handlers/UpdateUserReportingSettings.ashx into the browser I can hit break point in my Handler.
So changed my URL in ajax call to :
url: '/MyWebsite/Handlers/UpdateUserReportingSettings.ashx',
and did a shift refresh to reload the js for page and hit the breakpoint.
function getData(url) {
$.getJSON(url, function(result) {
$('#formNav ul').append('<ul/>')
$.each(result, function() {
var list = $('#formNav li'),
listItem = $('<li/>'),
html = listItem.append($('<h5/>').text(this.name));
$.each(this.items, function() {
listItem.append($('<a />').attr('href', this.id).text(this.name))
});
list.append(html)
});
});
};
$(function(){
var Menu = {
$menu: $('.config-nav #formNav'),
$trades : $(".config-nav select#tradesmanList"),
$skills : $(".config-nav select#jobList"),
init: function(){
var $menu = Menu.$menu;
// Set menu up
$menu.children("li").addClass('closed');
$menu.find(".js-reveal").hide();
Menu.$skills.attr("disabled", "disabled");
Menu.$trades.on("change", function($skills){
Menu.$skills.removeAttr("disabled");
});
// bind to click on the item...
$menu.on("click", "h4", this.toggle);
},
toggle: function() {
// Toggle the hide show of the drill down menu
var $this = $(this),
$category = $this.parent();
console.log($this.parent().index());
var data = getData("test.json");
$category.addClass("loading").toggleClass("open");
$this.next(".reveal").delay(100).toggle(0, function(){
$category.Data;
$category.removeClass("loading");
});
}
};
Menu.init();
});
I have a function that returns json data , i then call this function in the Menu function to display the data however every time i click the button the data just keeps being generated instead i want it to display the data and then once it is clicked again hide the data? if anyone has any advice that would be great.
Thanks.
When ever you call the toggle function You seem to get the data using
var data = getData("test.json"); and then use it to populate the list..
Why don't you move the getData method to outside the toggle function and instead move it to to init function .. Look's like it should be fine then..
I'm currently writing a JQuery plugin that loads colors from a JSON web service into a drop down list.
The drop down list background-color changes according to the selected value. For the most part it is working. on any regular change it works as expected, the problem I am having is on the initial page load I am using triggerHandler("change"); and it triggers but I seem to be getting an undefined error on the selected value from the drop down list on page load so it doesn't trigger the color change on the drop down list
My code is:
$.fn.bindColorsList = function (options) {
var defColor = options.defaultColor;
var svcUrl = options.svcurl;
//var f_target = options.filterTarget;
var $this = this;
$.ajax({
url: options.svcurl,
dataType: 'json',
/*data: { filter: src_filt },*/
success: function (fonts) { fillcolors(fonts, $this) },
error: function () { appendError(f_target, "colors failed to load from server") }
});
this.on("change", function (event) {
log($(event.target).attr("id") + " change detected");
//change ddl dropdown color to reflect selected item ;
var hcolor = $this.find('option:selected').attr("name");
$this.attr("style", "background-color:" + hcolor);
});
function fillcolors(colors, target) {
$(target).empty();
$.each(colors, function (i, color) {
$(target).append("<option name='"+color.HexValue+"' value='" + color.Name + "' style='background-color:"+color.HexValue+"'>"+color.Name+"</option>");
});
};
//in a seperate file
$(document).ready(function () {
$("#dd-font-color").bindColorsList({ svcurl: "/home/colors"});
$("#dd-back-color").bindColorsList({ svcurl: "/home/colors" });
});
You are doing an AJAX request to populate your dropdown which, by the way, is an asynchronous one. In this case you need to trigger the event in the success callback of the AJAX request.
var $this = this;
// Bind the onchange event
$this.on("change", function (event) {
..
});
// Populate using AJAX
$.ajax({
...
success: function (fonts) {
// Populate the values
fillcolors(fonts, $this);
// Trigger the event
$this.trigger("change");
},
...
});
That's it.