Set a cell value and keep it editable in inline editing - javascript

I have to change a cell value by code and keep it editable. With this code, I can change the value of the other cell, but the cell 'paidHour' change to a non-editable state.
How to make it editable again?
editoptions: { dataEvents: [{ type: 'keyup', fn: function (e) {
var rowId = $(e.target).closest("tr.jqgrow").attr("id");
var total = parseInt(e.target.value, 10);
var paidWeek = parseInt($("#List").getCell(rowId, 'paidWeek'), 10);
var addHourBank = 0;
if (total >= paidWeek) {
addHourBank += (total - paidWeek);
total = paidWeek;
}
$("#List").setCell(rowId, 'paidHour', total);

I am not sure that I understand you correct. It's important to distinguish editing and editable cells/rows. The editable is the row or the cell which can be edited with respect of form editing, inline editing or cell editing. Probably the cell are editing currently and you want to change the value of the cell. In the case you can't use setCell method. Instead of that you have to get the <td> as DOM or as jQuery wrapper and then set value of the child <input> element of the cell.
For example you can use getColumnIndexByName function defined as following
var getColumnIndexByName = function (grid, columnName) {
var cm = grid.jqGrid('getGridParam', 'colModel'), l = cm.length, i;
for (i = 0; i < l; i++) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
}
It gets you the index of the column inside of the row. So you can split the line
var rowId = $(e.target).closest("tr.jqgrow").attr("id");
into
var $tr = $(e.target).closest("tr.jqgrow"), rowId = $tr.attr("id");
The $tr represents the jQuery wrapper of the DOM of <tr>. So to get the <td> cell for 'paidHour' you can use
var iCol = getColumnIndexByName ($(this), 'paidHour');
var $td = $tr.find(">td:nth-child(" + (iCol + 1) + ")");
and to change the value of the cell you can use
$td.find("input").val(total);

Related

How to make a button functional when loaded into a row from local storage in javascript

//loops through all rows and cells and saves them into local storage as objects
window.onbeforeunload = function() {
var rows = document.getElementById('firsttable').tBodies[0].rows;
for (var i = 0; i < rows.length; i += 1) {
localStorage.setItem(i, JSON.stringify({
Item: rows[i].cells[0].innerHTML,
filling1: rows[i].cells[1].innerHTML,
filling2: rows[i].cells[2].innerHTML,
filling3: rows[i].cells[3].innerHTML,
Stock: rows[i].cells[4].innerHTML,
min: rows[i].cells[5].innerHTML,
sold: rows[i].cells[6].innerHTML,
closeAcc: rows[i].cells[7].innerHTML,
sell: rows[i].cells[8].innerHTML,
dltButton: rows[i].cells[9].innerHTML
}));
};
};
//loads the objects into rows with the values in their cells
window.onload = function() {
var r = 0,
c = 0;
//load the actual data from localstorage into html rows
for (x in localStorage) {
var row = table.insertRow(r),
obj = JSON.parse(localStorage.getItem(x));
for (i in obj) {
var cell = row.insertCell(c);
cell.innerHTML = obj[i];
c += 1
}
r += 1;
c = 0;
}
};
//where the problem is
$(function() {
$('table td').click(function(e) {
if (e.target.id === "Sellbtn") {
var sell = prompt("Enter the amount");
for (var i = 0; i < table.length; i += 1) {};
this.parentNode.parentNode.cells[4].innerHTML = parseInt(this.parentNode.parentNode.cells[4].innerHTML) - sell; //not working and no when put inside the for loop it doesn't work idk why
} else if (e.target.id === "Deletebtn") {
return false;
} else {
var ask = prompt("Input");
$(this).html(ask);
}
});
});
So i insert a row and add the details to the cells and such then as explained in the snippet the first function saves available the rows and cells into a JSON stringified object in the localstorage when the user is closing the browser and then loads them up during onload the problem is with the buttons idk how to make them function after the onload(user closes and opens again). So imagine this you have your HTML table with several rows and their cells and each row has the two buttons(sell and delete) how do i make them function when the user opens up the application again? and btw the buttons are both dynamically added using createElement() when the row is originally added
Try delegating the click event you have on your table rows since they're being created after the DOM loads:
$('table').on("click", "td", function(e) {

jQuery Add row to table with dynamic ids'

http://jsfiddle.net/waH5S/6/
function add_row_retail() {
$(document).ready(function () {
var table = document.getElementById("Retail");
var row = table.insertRow(-1);
var row_id = $('#Retail').val('tr[id]:last');
console.log(row_id);
var cell_init = row.insertCell(-1);
cell_init.innerHTML = "blank";
});
}
I am trying to get the id of the table row(<tr>) before the added row, and then add 1 to this, with proper parseint(...). Then doing the same with the cell (<td>) next, so that every cell has a unique id for each table. I can't seem to find the row's id.
HERE IS THE "CORRECT" CODE FOR MY QUESTION
function add_row_retail() {
var table = document.getElementById("Retail");
// Row id
var row_id = $('#Retail tr:last').attr('id');
var row = table.insertRow(-1);
var next_row_id = "tr_" + (1+parseInt(row_id.match(/\d+/)[0],10));
$(row).attr('id', next_row_id);
for (var i = 0; i < 8; i++) {
var cell_id = $('#Retail td:last').attr('id');
console.log(cell_id);
var next_cell_id = "td_" + (1+parseInt(cell_id.match(/\d+/)[0],10)); console.log(next_cell_id);
var cell = row.insertCell(-1);
$(cell).attr('id', next_cell_id);
$(cell).innerHTML = "blank";
}
}
Rather than $('#Retail').val('tr[id]:last'); I think you want:
var row_id = $('#Retail tr:last').attr('id')
This selector finds the last tr under the #Retail element, and returns its id attribute.
jQuery last selector: http://api.jquery.com/last-selector/
Next problem: IDs cannot start with numbers. Rename your IDs like "tr_1", "tr_2", etc.
Next problem: To extract the numbers from a string:
"tr_123".match(/\d+/)[0]; // returns 123.
Add 1 to it:
var next_id = "tr_" + (1+parseInt("tr_123".match(/\d+/)[0],10));
Then, set your new id.
var row = table.insertRow(-1);
...
$(row).attr('id', next_id);

Kendo grid change multiple selected cells value

Let's say I have few rows of data populated with numbers. I want to select multiple cells and then on click on a button outside the grid change their values to some other number, let's say '8'. See the sample.
The guys at Telerik gave me this solution:
$(".change").click(function () {
var grid = $("#Grid").data("kendoGrid");
var cellsToChange = grid.select();
for (var i = 0; i < cellsToChange.length; i++) {
var item = grid.dataItem($(cellsToChange[i]).closest("tr"));
item.ProductName = "new value";
}
grid.refresh();
});
But the problem is that I don't know which cells will be selected, so I can't work with item.ProductName, for example. Is there a way to set the value of all selected cells directly, something like cellsToChange[i].value?
You can either get the column name from grid.columns or from the corresponding th element. use the grid.cellIndex method to select the correct column:
$("#change").click(function() {
var selected = grid.select();
var header = grid.thead;
for (var i = 0, max = selected.length ; i < max ; i++) {
var index = grid.cellIndex(selected[i]);
var th = $(header).find("th").eq(index);
// could also use grid.columns[index].field
// (not sure if this gets reordered on column reorder though)
var field = $(th).data("field");
var item = grid.dataItem($(selected[i]).closest("tr"));
item[field] = "new value";
}
grid.refresh();
});
Regarding your comment:
dataItem.set() causes the <tr> elements to get removed from their context (because grid.refresh() will create new rows for the view), and because of that, grid.dataItem() won't give you the expected result with the old DOM elements you still have a reference to.
If you want to use dataItem.set(), you can try something like this as a work-around:
$("#change").click(function () {
var selected = grid.select(),
header = grid.thead,
dataItem,
index,
field,
value,
th;
for (var i = 0, max = selected.length; i < max; i++) {
dataItem = grid.dataItem($(selected[i]).closest("tr"));
index = $(selected[i]).index();
th = $(header).find("th").eq(index);
field = $(th).data("field");
value = "new value " + i;
setTimeout(function (dataItem, field, value) {
return function () {
dataItem.set(field, value);
}
}(dataItem, field, value), 5);
}
});
(demo)
You have to retrieve the ColumnList of your grid first and then loop through it
$(".change").click(function () {
var grid = $("#Grid").data("kendoGrid");
var columnsListOfView = grid.columns;
var cellsToChange = grid.select();
for (var j = 0; i < cellsToChange.length; i++) {
var item = grid.dataItem($(cellsToChange[i]).closest("tr"));
for (var j = 0; j < columnsListOfView.length; j++) {
//Here columnsListOfView[j].field will give you the different names that you need
var field=columnsListOfView[j].field;
item[field] = "new value";
}
}
grid.refresh();
});

get selectedvalue of dropdownlist items added from javascript

Hi I have added some items to asp:DropDownList from javascript. Like this
if (document.getElementById("<%=gdview.ClientID %>")!=null)
{
var rows = document.getElementById("<%=gdview.ClientID %>").getElementsByTagName('tr');
var cells = rows[1].getElementsByTagName('td');
//alert(cells)
i = 2;
while (i < cells.length)
{
document.getElementById("<%=ddl_noofCols.ClientID %>").options[i] = new Option(i + 1, i);
i++;
}
document.getElementById("<%=ddl_noofCols.ClientID %>").options[2].selected =true;
alert(document.getElementById("<%=ddl_noofCols.ClientID %>").options[2].text);
}
here gdview is gridview. no of columns of gridview are added to dropdownlist
default is options[2] is selected. I cannot the get selecteditem/selectedvalue using ddl_noofCols.SelectedValue which returns null.
How can I get the selectedvalue.
Thanks in advance.
You may want something like:
var table = document.getElementById("<%=gdview.ClientID %>");
var select = document.getElementById("<%=ddl_noofCols.ClientID %>");
var cells;
if (table) {
cells = table.rows[1].cells;
for (var i=2, iLen=cells.length; i<iLen; i++) {
select.options[i] = new Option(i + 1, i);
}
select.options[2].selected = true;
alert(select.options[2].text);
// To get the current value of the select,
// use the value property:
alert(select.value);
}
The value of the currently selected option is available as select.value. If the selected option has no value attribute or property, then the value of the text property is returned except in IE 8 and lower, where you must use something like:
var value = select.value;
if (!value) {
value = select.options[select.selectedIndex].text;
}

Drag and Drop div into table and get the data value

I set the div data value in table cells, what I want is how to get the div data value, while drop.
In my code, I set the data in the table like this
<script type="text/javascript">
function createDynamicTable(tbody, rows, cols) {
if (tbody == null || tbody.length < 1) return;
for (var r = 1; r <= rows; r++) {
var trow = $("<tr>");
for (var c = 1; c <= cols; c++) {
var cellText = "Cell " + r + "." + c
$("<td>")
.addClass("tableCell")
.text(cellText)
.data("col", c)
.appendTo(trow);
}
trow.appendTo(tbody);
}
}
In my code, on clicking the cell of table, I get the row and column data div values
$(document).ready(function() {
createDynamicTable($("#tbl"), 10, 5);
$("#tbl td.tableCell")
.click(function() {
alert("Clicked Col=" + $(this).data("col"));
});
});
it is working perfectly
for full code view the site:
http://blogs.microsoft.co.il/blogs/linqed/archive/2009/03/04/generating-html-tables-with-jquery.aspx
I try like this but I cann't getting the table cell data value on stop event. How to get the setted data value in drag and drop.
$(".drag").draggable({
stop: function (ev, ui) {
var pos = $(ui.helper).offset();
var oldData = $("#tbl td.tableCell").data('col');
alert(oldData);
}
});
Help me to get the data value in drag and drop.
Thanks in advance.
Drag and Drop could be restructuring the DOM. Try Using jQuery.live instead of jQuery.click (if supported by your jQuery version) to bind the click event:
$("#tbl td.tableCell")
.live('click', function() {
alert("Clicked Col=" + $(this).data("col"));
});
Since .live() is deprecated you may also want to try the .on() method (if using jQuery 1.7.x).

Categories

Resources