I have a view with a table with single selection mode and a button in its toolbar to delete selected row.
Though when I press the button, it deletes all the rows instead.
My code:
View file:
<template data-controller-name="myapplication.myview2">
<div data-sap-ui-type="sap.ui.table.Table" id="tb1" data-width="100%" data-title="Person Table"></div>
</template>
Controller File:
onInit: function() {
try {
var oTab = [
// the table content
];
var oToolbar = new sap.ui.commons.Toolbar();
oToolbar.addItem(new sap.ui.commons.Button({text: "Delete selected row",
press: function() {
try {
var newTab = this.getParent().getParent();
var index = newTab.getSelectedIndex();
if (index == -1)
alert("No row selected");
else {
var currModel = newTab.getModel();
var selectedRow = newTab.getRows()[index];
newTab.removeRow(selectedRow);
currModel.setData({table: newTab});
newTab.bindRows("/table");
}
} catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}}));
this.byId("tb1").setToolbar(oToolbar);
this.byId("tb1").setVisibleRowCount(5);
this.byId("tb1").setNavigationMode(sap.ui.table.NavigationMode.Paginator);
// Columns definition should be HERE
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({table: oTab});
this.byId("tb1").setModel(oModel);
this.byId("tb1").bindRows("/table");
} catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
},
// More functions....
Any ideas please?
You need to remove row from model, not from table directly.
Here is an example on how to do this.
http://jsbin.com/yewula/1/edit
Like many folks have suggested, we should removed it from the model. Since table is binded to the model, table will refresh accordingly.
-D
In your press function for the delete button, get more details about the table:
var tableIndex = newTab.getSelectedIndex();
var context = newTab.getContextByIndex(tableIndex);
var path = context.getPath();
In the variable path you will then find the data index that corresponds to the table row index. Use this data index to remove the row from the model.
currModel.oData.table.splice(data_index, 1);
Afterwards, all that should be needed is a refresh of the model to inform the controls about the changed data. And, for the user it might also be nice if the selection in the table gets reset as well.
currModel.refresh();
newTab.setSelectedIndex(-1);
Related
I have created a dynamic table in html click here to view image the rows are created dynamically in javascript please refer the image click here to view image the data for table is fetched from firebase.
The problem I am facing is that the rows are getting added at the end of the table repeatedly resulting in duplicate rows please refer the image click here to view image how do I remove old rows and add new updated rows using javascript.
I have updated the snapshot.forEach loop with comments.
snapshot.forEach(function (data) {
var val = data.val();
var trow = document.createElement('tr');
var tdata = document.createElement('td');
var tdata1 = document.createElement('td');
tdata.innerHTML = val.Name;
tdata1.innerHTML = val.Votes;
trow.appendChild(tdata);
trow.appendChild(tdata1);
// set the Name as data-id attribute
// which can be used to query the existing row
tdata.setAttribute('data-id', val.Name);
// append the trow to tbdy
// only if there's no row with data-id value of val.Name
// otherwise update the vote column of the existing row
var existingRow = tbdy.querySelector('[data-id="' + val.Name + '"]');
if (!existingRow) {
tbdy.appendChild(trow);
} else {
existingRow.querySelectorAll("td")[1].innerHTML = val.Votes;
}
});
We have a form where we need to develop dynamic table form. We have used select2 plugin to multi select the dropdown. But when we add new row select2 gets disabled and when we reinitialize the following problem occurred. So please suggest how to resolve this issue.
function addTableRow(table) {
var $ttc = $(table).find("tbody tr:last");
var $tr = $ttc.clone();
$tr.find("input,select").attr("name", function () { // find name in the cloned row
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts from id, including index
if (parts) {
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new name
}
}).attr("id", function () { // change id also
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts
if (parts) {
return parts[1] + "_" + ++parts[2] + "__" + parts[3]; // build new id
}
});
$tr.find("span[data-valmsg-for]").attr("data-valmsg-for", function () { // find validation message
var parts = $(this).attr("data-valmsg-for").match(/(\D+)\[(\d+)]\.(\D+)$/); // extract parts from the referring attribute
if (parts) {
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new value
}
});
//$ttc.find(".new-row").attr("class", "btn btn-danger remove-row").attr("title", "Delete row").unbind("click").click(deleteRow).empty().append("<i class='fa fa-minus'> </i>"); // change buttin function
if (table == "#skills-table") {
$tr.find(".new-row").click(addRow); // add function to the cloned button
}
if (table == "#uniqueIdenifier-table") {
$tr.find(".new-row").click(addUniqueRow); // add function to the cloned button
}
if (table == "#OtherBankList-table") {
$tr.find(".new-row").click(addOtherBankListRow); // add function to the cloned button
}
if (table == "#childorganisation-table") {
$tr.find(".new-row").click(addOtherChildListRow); // add function to the cloned button
}
// reset fields in the new row
$tr.find("select").val("");
$tr.find("input[type=text]").val("");
$tr.find("input[type=hidden]").val("");
// add cloned row as last row
$(table).find("tbody tr:last").after($tr);
// Find the affected form
var $form = $tr.closest("FORM");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
var _select = $tr.find('.select2');
if (_select) {
//console.log(_select);
initializeSelect2(_select);
}
// We could re-validate with changes
// $form.validate($form.data("unobtrusiveValidation").options);
};
function initializeSelect2(selectElementObj) {
//selectElementObj.select2("destroy");
selectElementObj.select2();
}
I would like to add a doubleclick event handler to table cell AFTER the table was "downloaded" from a servlet and "inserted" by javascript.
I have a javascript cycle that iterate on a xml response to map datas ini table. Said that a cell can be
<td class='red' ></td>
I want to add a function on that cell, I've tried several solution, but none works.One is:
$(".red").on("dblclick",myfunction);
Help?
Update:
Table constructor ofter response received
function handleResponse(responseXML) {
var i;
var x=responseXML.getElementsByTagName("row");
var out="<table><tr><th >Description</th><th >State</th><th>Note</th></tr>";
for(i=0;i<x.length;i++){
out+="<tr>";
var Description = x[i].getElementsByTagName("Description")[0].childNodes[0].nodeValue;
var State = x[i].getElementsByTagName("State")[0].childNodes[0].nodeValue;
var note = x[i].getElementsByTagName("Note")[0].childNodes[0];
var note_text=" ";
if (!(typeof note === "undefined") && !(note=='null')) {
note_text=note.nodeValue;
}
out += "<td>"+Description+ "</td>";
if(State==0)
out+="<td class='white' ></td>";
else if(State==1)
out+="<td class='red' ></td>";
else if(State==2)
out+="<td class='yellow' ></td>";
else if(State==3)
out+="<td class='green' ></td>";
out+="<td>" + note_text + "</td></tr>";
}
var output = document.getElementById("mytable");
out+="</table>";
$().on("click",".red",update()); //here is the point
output.innerHTML=out;
}
Update:
Based on your comments you can try this:
When you print the td change the template a little:
out+="<td class='red' ondblclick='openModal()'></td>";
And then in your js file add something like this.
$(document).ready(function() {
function openModal() {
alert( "Double clicked." );
// Or call your other function here...
};
});
You can do it with several ways also, check here: http://www.w3schools.com/jsref/event_ondblclick.asp
I have a delete function within a function where if the user clicks on the "Delete" button, it displays a message stating that a file has been deleted. The code which does this is below:
$("#imagemsg").html(data);
But the problem is that let's say that I have 4 table rows and I delete a file in the 3rd row, the message should be displayed in the 3rd row only but instead it is displayed in the first row. Another example is that let's say that I have 8 table rows and I delete a file in the 6th row, the message should be displayed in the 6th row only but instead it is displayed in the first row.
Why is the message that is suppose to appear after a file is deleted is always displayed in the first row and not within the row the file has been deleted from?
Below is full code:
var counter = 0;
counter++;
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 1){
result = '<span id="imagemsg'+counter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else {
result = '<span id="imageemsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$("#imagemsg" + counter).html(data);
});
$(this).parent().remove();
});
return true;
}
Below is the deleteimage.php script where the delete message is retrieved from:
<?php
$image_file_name = $_GET["imagefilename"];
echo "$image_file_name was Deleted";
unlink("ImagesFilesFolder/$image_file_name");
?>
The problem seems to be this:
.done(function(data) {
$("#imagemsg" + counter).html(data);
You set counter like this
var counter = 0;
counter++;
But you never seem to refer to the variable again. In any case, this variable is global - the command above will always target the ID with the current number of the counter, so it will not target the tr corresponding to the clicked button.
Since you use
$(this).parent().remove();
I assume that the parent is the tr concerned? In this case you could use a class instead of an ID 'imagemsg' and then do
$(this).parent().find(".imagemsg").html(data);
This would target the message inside the same row of the button.
There are two things I would like help with please. I need help accessing the currently edited existing row in the Radgrid, as as well as the index of the Edit form when trying to add a new record to the table/
function OnClientSelectedIndexChanged(sender, eventArgs) {
var item = eventArgs.get_item();
// alert(item.get_value());
grid = $find("<%= rgSecurity.ClientID %>");
var MasterTable = grid.get_masterTableView();
var selectedRows = MasterTable.get_selectedItems();
// alert("about to get to grid");
alert(selectedRows.length);
if (selectedRows.length > 1) {
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
alert(row);
inputField = MasterTable.getCellByColumnUniqueName(row, "Item")
alert(inputField);
if (inputField) {
inputFieldValue = inputField.value
break;
}
}
}
else
{
// alert(inputField);
}
window.radopen('<%=PopLink %>?sel=' + item.get_value() + "&avail=" + inputFieldValue, "UserRoleDialog");
return false;
}
The currently edited grid row can be retrieved on the server using the EditItems[0] collection of the master table or through the e.Item argument inside the EditCommand server event handler. The index of the edited row can be fetched from the ItemIndex property of the item referenced as explained in the first sentence.