Add, edit and delete function to my javascript - javascript

I'm looking to add edit and delete functionality to the following JavaScript and I'm not sure where exactly to start.
This functions just fine as a input add but It needs to be editable and deletable. Is Javascript the way to go here?
HTML
<table width="600px" class="setpoint-form-table">
<tr>
<td colspan="5">
<p style="font-size:16px; float:left;">First Name / Last Name Table Post and Edit</p>
</td>
</tr>
<tr>
<td colspan="5" height="20px"></td>
</tr>
<tr>
<input type="text" id="RowPlaceholder2" style="visibility:hidden;" />
<td width="100px" style="font-size:14px">First Name</td>
<td><input type="text" id="fName" class="setpoint-textbox" /></td>
<td width="100px" style="font-size:14px;">Last Name</td>
<td><input type="text" id="lName" class="setpoint-textbox" /></td>
<td><button type="button" id="edit">Edit</button></td>
</tr>
<tr>
<td colspan="5" height="20px"></td>
</tr>
<tr>
<td colspan="5"><button type="button" onclick="HvacStandards()">Submit</button></td>
</tr>
<tr>
<td colspan="5">
<br />
<br />
<table width="600px" id="testingWithEdit">
<tr>
<td style="background-color:#fff; color:#00468C; border-bottom:1px solid #000; border-right:1px solid #000;">First Name</td>
<td style="background-color:#fff; color:#00468C; border-bottom:1px solid #000;">Last Name</td>
</tr>
</table>
</td>
</tr>
</table>
JavaScript
function HvacStandards() {
var rowID = document.getElementById("RowPlaceholder2").value;
var firstName = document.getElementById("fName").value;
var lastName = document.getElementById("lName").value;
var sHtml = "<tr>" +
"<td id=\"firstName" + rowID + "\">" + firstName + "</td>" +
"<td id=\"lastName" + rowID + "\">" + lastName + "</td>" +
"</tr>";
$("#testingWithEdit").append(sHtml);
rowID++;
document.getElementById("RowPlaceholder2").value = rowID;
document.getElementById("fName").value = "";
document.getElementById("lName").value = "";
}

Here's just one of the many ways to do this:
In this fiddle, I simply added an extra column to sHTML containing edit and delete buttons that call editRow() and deleteRow() respectively, both passing the parameter of the rowID.
I then defined two new global variables, newRow and currentRow. I then modified HvacStandards use newRow as the RowID. Additionally, I modified it to switch to saveEdits if currentRow is not -1, so that hitting the submit button saves the edits instead of just creating a new row.
Then I created the the editRow function that fills the textboxes with the html contained within firstName+rowID and lastName+rowID, and then set currentRow to the rowID.
The saveEdits function then modifies the html of the table rows to the new values from the inputs, clears the inputs, and then resets currentRow to -1 so hitting submit will add a new row next time.
Finally, the deleteRow function simply removes the row from the dom. (I added an id to the tr in sHTML so that the row as a whole can be identified).
Let me know if this all makes sense and does what you need it to do :)

Related

Dynamically change text in table using by clicking a checkbox

I have a data in JSON format and I convert it to a HTML table. Now I want to
change the text from False to True if I check the checkbox. How can I do that?
Here is the code for creating the HTML table:
$.each(result, function (index, value) {
var Data = "<tr>" +
"<td class='' id='stdID' >" + value.StudentID + "</td>" +
"<td class='' id='stdRol'>" + value.RollNo + "</td>" +
"<td class='' id='stdName'>" + value.FirstName + "</td>" +
"<td class='cbx' value='1'><input type='checkbox' id='cc"+index+"'><span id='checkbox-value'> False</span></td>" +
"</tr>";
SetData.append(Data);
This is the result of this: output
To achieve what you require you need to use a delegated event handler, as you dynamically append the rows after the page has loaded, to hook to the change event of the checkboxes. Then you can set the text of the sibling span element based on the checked property. Something like this:
$('table').on('change', ':checkbox', function() {
$(this).next('span').text(this.checked);
});
span.checkbox-value { text-transform: capitalize; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="stdID">value.StudentID</td>
<td class="stdRol">value.RollNo</td>
<td class="stdName">value.FirstName</td>
<td class="cbx" value="1">
<input type="checkbox" id="cc1">
<span class="checkbox-value">False</span>
</td>
</tr>
<tr>
<td class="stdID">value.StudentID</td>
<td class="stdRol">value.RollNo</td>
<td class="stdName">value.FirstName</td>
<td class="cbx" value="1">
<input type="checkbox" id="cc2">
<span class="checkbox-value">False</span>
</td>
</tr>
</table>
You should note that your loop is creating multiple elements which have the same id, which is invalid HTML. In the example above I've changed them to classes instead.
Another way around to achieve your desired output
$(document).on('change', '.changeStatus', function() {
var row = $(this).closest('tr');
if($(this). prop("checked") == true){
row.find('.changeValue').html('True');
} else {
row.find('.changeValue').html('False');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>Id</td>
<td>Roll_no</td>
<td><input type="checkbox" class="changeStatus"></td>
<td class="changeValue">False</td>
</tr>
<tr>
<td>Id</td>
<td>Roll_no</td>
<td><input type="checkbox" class="changeStatus"></td>
<td class="changeValue">False</td>
</tr>
<tr>
<td>Id</td>
<td>Roll_no</td>
<td><input type="checkbox" class="changeStatus"></td>
<td class="changeValue">False</td>
</tr>
</tbody>
</table>

HTML table with editable fields accessed in javascript.

I am trying to build a table that will allow users to change the value of a cell(s) and then "submit" that data
to a JavaScript (only please) method that turns the tables data into a json dataset.
I started by trying to updated the value of just one field. QTY in this case. I am able to loop over the table and get the static values, but I am not able to catch the user input value.
question: What is a JavaScript only (if possible) way to capture user change(able) values from a table?
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).innerHTML;
//alert("qty: " + wty);
qty = qty.substr(oCells.item(2).innerHTML.indexOf('value=') + 7);
qty = qty.substr(0, qty.indexOf('" class='));
//alert(qty);
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
THANK YOU
Instead of selecting the entire td element, retrieve only what you really need using querySelector (or use jQuery if possible). Find the input element and access the value, it's a lot easier than doing all of that unecessary parsing of the inner html of the entire cell.
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).querySelector(".mdl-textfield__input").value;
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
You need to use document.getElementById('value2').value instead of .innerHTML.indexOf('value=')
You're making yourself a lot of work here. You have a table. All you need to do is convert that to JSON. I would suggest you look at the library below that does that in around one line of native java-script.
http://www.developerdan.com/table-to-json/

Jquery - add new rows table into wrong div

I am pretty new to jquery. I have the following code. Here I wants to get new rows in the table on clicking add button in Fill 3. I succeend to add that row, but when I get new divs then I wants to get new rows in the table on clicking add button in Fill 3. It added into wrong div.
can someone tell me what mistake I've done here?
var id = 0; //global id to create unique id
$(document).ready(function() {
//attach click event to element/button with id add and remove
$("#add,#remove").on('click', function() {
var currentElemID = $(this).attr('id'); //get the element clicked
if (currentElemID == "add") { //if it is add elem
var cloneParent = $("#dataTes").clone(); //clone the dataTes element
id=$("div[id^=dataTes]").length + 1;//get the count of dataTes element
//it will be always more than last count each time
cloneParent.find('[id]').each(function() {
//loop through each element which has id attribute in cloned set and replace them
//with incremented value
var $el = $(this); //get the element
$el.attr('id', $el.attr('id') + id);
//ids would now be add1,add2 etc.,
});
cloneParent.attr('id', cloneParent.attr('id') + id);//replace cloneParent id
cloneParent.appendTo('#result');//append the element to fieldset
$("#remove").show();//show remove button only if there is more than one dataTes element
} else {
$("div[id^=dataTes]:last").remove();
//just remove the last dataTes
//[id^=dataTes]:last annotates remove last div whose id begins with dataTes
//remember we have id like dataTes1,dataTes2 etc
if($("div[id^=dataTes]").length==1){
//check if only one element is present
$("#remove").hide();//if yes hide the remove button
}
}
});
});
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 1) {
table.deleteRow(rowCount - 1);
}
else {
alert("Tidak dapat menghapus semua baris!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="result">
<legend>Test</legend>
<input type="submit" class="button" id="add" value="+" title="#">
<input type="submit" class="button" id="remove" value="-" style="display:none;" title="#">
<!--hide the remove button with display:none initially-->
<div id="dataTes">
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:10px;" width="97%">
<tr>
<td width="100px">Test</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:5px;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill 1</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<tr>
<td width="2px"></td>
<td width="100px">Fill 2</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<table id="dataIP" align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill 3</td>
<td width="2px">:</td>
<td width="2px">
<input type="text" name="usrname">
</td>
<td>
<input type="submit" class="button" value="+" onClick="addRow('dataIP')" title = "#">
<input type="submit" class="button" value="-" onClick="deleteRow('dataIP')" title = "#">
</td>
</tr>
</table>
</table>
</table>
</div>
</fieldset>
Thanks in advance!
<table id="dataIP" align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill 3</td>
<td width="2px">:</td>
<td width="2px">
<input type="text" name="usrname">
</td>
<td>
<input type="submit" class="button" value="+" onClick="addRow('dataIP')" title = "#">
<input type="submit" class="button" value="-" onClick="deleteRow('dataIP')" title = "#">
</td>
</tr>
</table>`
so what will we do here is that we will change addRow(this) instead of addRow('dataIp') because we know that "this" keyword has a high priority in terms of passing the ID of the element .. the "this" keyword has a general purpose vs passing of id into a function .. just try changing all parameter to the "this".
function addRow(tableID) {
var par = tableID.parentNode.parentNode.parentNode.id;
var table = document.getElementById(par);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
this is what ive done when I change the parameter of the add and delete function in your input i get the param parent node the element for the purpose of specific element inside the parent element...
}
by the way.. you must change your third index table to tbody. the result of getting the parentnode will be a tbody. because putting table inside a table is redundant window read it as tbody
we must follow the rule
<table>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>

For loop with array doesn't work with innerHTML

I have a div with the ID="ranking" and I'd like to put there some info of a JavaScript array with a table where every row has tow columns: one for dados[i][25] and other for dados[i][26].
My code is this:
function dadosRanking(dados){
document.getElementById("ranking").innerHTML += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
for(var i=1;i<6;i++)
{
document.getElementById("ranking").innerHTML += '<tr><td>' + dados[i][25] + '</td><td>' + dados[i][26] + '</td></tr>';
}
document.getElementById("ranking").innerHTML += '</table>';
}
The code I expect was this:
<table class="table">
<tr>
<td valign="middle" class="question" colspan=2>
<h1>RANKING (+ PONTOS)</h1>
</td>
</tr>
<tr>
<td>PONTOS</td>
<td>UTILIZADOR</td>
</tr>
<tr>
<td>
100
</td>
<td>
Username
</td>
</tr>
</table>
However, the HTML code script write is this:
<table class="table">
<tr>
<td valign="middle" class="question" colspan=2>
<h1>RANKING (+ PONTOS)</h1>
</td>
</tr>
<tr>
<td>PONTOS</td>
<td>UTILIZADOR</td>
</tr>
</table>
"100Username"
Everytime you update innerHTML the browser will parse it and render it, to do that it will also try to 'fix' your HTML. This can have unintended consequences. Instead of pushing to innerHTML with a partial table definition, collect the HTML in a separate value and push to innerHTML once.
function dadosRanking(dados){
var s = "";
s += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
for(var i=1;i<6;i++) {
s += '<tr><td>' + dados[i][25] + '</td><td>' + dados[i][26] + '</td></tr>';
}
s += '</table>';
document.getElementById("ranking").innerHTML += s;
}
After
document.getElementById("ranking").innerHTML += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
innerHTML becomes:
<table class="table">
<tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr>
<tr><td>PONTOS</td><td>UTILIZADOR</td></tr>
</table>
Note that the table has been closed!
After
document.getElementById("ranking").innerHTML += '<tr><td>foo</td><td>bar</td></tr>';
innerHTML becomes
<table>..</table>
foobar
<tr> and <td> are not valid outside of a table context so they're removed.
After
document.getElementById("ranking").innerHTML += '</table>';
innerHTML doesn't change because </table> doesn't do anything, there is no table to close.

How to take value from cell in javascript

I have a grid setter in javascript like this :
function AddMdrPymt(){
var f = document.frmPL0011;
var grid = document.getElementById("mdrPymtGrid");
var numRows = grid.rows.length;
grid.insertRow(numRows);
grid.rows[numRows].insertCell(0);
grid.rows[numRows].insertCell(1);
grid.rows[numRows].insertCell(2);
grid.rows[numRows].insertCell(3);
grid.rows[numRows].cells[0].innerHTML = "<input type='checkbox' value='" + curRow + "' name='__mdrPymt' id='__mdrPymt'>";
grid.rows[numRows].cells[1].innerHTML = "<table border='0' align='center'><tr align='center'><td><input type='text' onkeyPress='checkNumber(this)' name='txt_strtAmnt' id='txt_strtAmnt' class='" + txtclass + "' maxlength='18' size='25' fieldName='<%=LangFormatter.getString("PL0011_LoanStartAmnt", true)%>' onblur='checkData(this)' value = '" + val + "' "+dsb+"></td></tr></table>";
grid.rows[numRows].cells[2].innerHTML = "<table border='0' align='center'><tr align='center'><td><input type='text' onkeyPress='checkNumber(this)' name='txt_endAmnt' id='txt_endAmnt' class='portlet-form-input-field' maxlength='18' size='25' fieldName='<%=LangFormatter.getString("PL0011_LoanEndAmnt", true)%>' onblur='checkData2(this)'></td></tr></table>";
curRow += 1;
And this is the grid HTML, the HTML code for the grid tittle, and the function above is function when user press add button
<table width="95%" align="center">
<tr>
<td>
<input name="addBtn" id="addBtn" type=button class='btn' onmouseover="this.className='btnHov'" onmouseout="this.className='btn'" value="<%=LangFormatter.getString("button_add",true)%>" onclick="AddMdrPymt()" tabindex="4">
<input name="delBtn" id="delBtn" type=button class='btn' value="<%=LangFormatter.getString("button_dlt",true)%>" onclick="delMdrPymt()" onmouseover="this.className='btn btnHov'" onmouseout="this.className='btn'" tabindex="5">
</td>
</tr>
<tr>
<td>
<table border="0" cellspacing="1" cellpadding="1" name="mdrPymtGrid" id="mdrPymtGrid" class="grid" width="95%">
<thead class="header">
<th width="1%"></th>
<th width="20%"><%=LangFormatter.getString("PL0011_LoanStartAmnt",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_LoanEndAmnt",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_FixAmntInd",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_FixCashAmnt",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_CashbackLoanAmnt",true)%></th>
</thead>
</table>
</td>
</tr>
<tr>
<td>
<input name="addBtn" id="addBtn" type=button class='btn' onmouseover="this.className='btnHov'" onmouseout="this.className='btn'" value="<%=LangFormatter.getString("button_add",true)%>" onclick="AddMdrPymt()" tabindex="6">
<input name="delBtn" id="delBtn" type=button class='btn' value="<%=LangFormatter.getString("button_dlt",true)%>" onclick="delMdrPymt()" onmouseover="this.className='btn btnHov'" onmouseout="this.className='btn'" tabindex="7">
</td>
</tr>
</table>
How to get value from txt_strtAmnt ?
Thank you
Please use the below code snippet to get the TABLE > TR > TD HTML elemnt value : -
/* To get any TD element value. If one input type inside TD element.
No need to mention the id name as we are getting the value using Tag Name. */
var grid = document.getElementById("mdrPymtGrid");
var tableRows = grid.getElementsByTagName("tr");
for (var j = 0 ; j <= tableRows.length; j++){
var tds = tableRows[j].getElementsByTagName("td");
for (var k = 0 ; k <= tds.length; k++){
var strtAmntVal = tds[k].getElementsByTagName('input')[0].value;
break;
}
}
If you are using grid with multiple rows then solution provided by #Arun will not work,
To make it work
1)find grid element first with document.getElementById('gridid');
2)iterate through its children
3)in that iteration loop find document.getElementById('txt_strtAmnt').value
I am sure that will help you !
also we can achieve through JQuery if you want

Categories