Delete function in JavaScript - javascript

I trying to delete row from a table but somehow is not working. Could please let me know how can I solve this one ?
here is my html with table and javascript:
<tbody class="items">
<tr>
<td> Data 1 </td>
<td> Data 2 </td>
</tr>
</tbody>
<tbody id="test">
<tr>
<td> </td>
<td> </td>
</tr>
</tbody>
$(".items tr").click(function() {
var value = parseInt($.trim(tableData[1]));
$("#test").append(
"<tr><td><input name='sm_invnumber[]' value='" +
$.trim(tableData[0]) +
"' style='width: 170px;' readonly ></td><td><input name='sm_amount[]' value='" +
$.trim(tableData[1]) +
"' style='width: 170px; text-align: right;' readonly ></td><td><span onclick='deleteRow(value, this)'> x </span> </td></tr>");
});
function deleteRow(value, row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('#test').deleteRow(i);
}
Here is the instruction that I am working with: Picking data by clicking on table (class= items) and place to them into table (id=test). there is a function with 'X'. I want to delete this row.
Helps are highly appreciated.

You seem to making your life very difficult. Why not simply add a class to the cell that has the cross and use jQuery to remove its containing row. For example:
<table>
<tbody id="test">
<tr><td>Data 1</td><td class="delete">x</td></tr>
<tr><td>Data 2</td><td class="delete">x</td></tr>
<tr><td>Data 3</td><td class="delete">x</td></tr>
</tbody>
</table>
$('.delete').click(function () {
$(this).parent().remove();
});
Fiddle

try this
function deleteRow(value, span)
{
$(span).closest("tr").remove();
}
or
function deleteRow(value, span)
{
var i=row.parentNode.parentNode.rowIndex;
$(document.getElementById('test')).children(":eq("+i+")").remove();
}

There are few poblems, try
jQuery(function () {
var tableData = [1, 'test'];
$(".items tr").click(function () {
var value = parseInt($.trim(tableData[1]));
$("#test").append(
"<tr><td><input name='sm_invnumber[]' value='" + $.trim(tableData[0]) + "' style='width: 170px;' readonly ></td><td><input name='sm_amount[]' value='" + $.trim(tableData[1]) + "' style='width: 170px; text-align: right;' readonly ></td><td><span onclick='deleteRow(\"" + value + "\",this)'> x </span> </td></tr>");
});
})
function deleteRow(value, row) {
$(row).closest('tr').remove();
}
Demo: Fiddle, another version

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>

Get row index of a table javascript

I know this question has been asked many times, I went through most of the suggestions and none of the solutions seem to be working for me.
I have a table in a modal in which I am allowing the user to make some changes. I then use these values to update the data in the database.
My table rows are created by echoing the HTML code
echo "<tr> ";
echo "<td > $row_counter </td>";
echo "<td style='width:200px' class='left_align' > $lstr_product_name </td>";
echo "<td > $lstr_department_name </td>";
echo "<td > <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='$lint_unit_cost' /> <input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='$lint_product_id' type='hidden'/> </td>";
echo "<td > $lint_quantity_counted </td>";
echo "<td > $lint_total_cost </td>";
To update the proper values in the database I need to get the product_id name which I know that I can get by
var x = document.getElementsByName("product_id")[0].value;
However I need to get the correct row index to be able to POST the correct product_id.
I have tried the following:
alert($(this).index());
But this always returns 0. The closest I got to a solution was by using
var rowID = $(this).closest('tr').index();
alert(rowID);
The problem with this is that my editable cell is "unit_cost" which is the 4th cell in the tr. This means that the closest tr is not the one that the row that the cell is in but the one below.
I have then tried
alert( "Row id: " + $("#tbl_store_product_sizes tr").this.rowIndex );
But also no luck. I have ran out of ideas, what is the proper way of doing this?
EDIT
All my javascript code is enclosed in the $(document).ready(function()
I am watching for the change of the unit_cost field using the following code
$(document.body).off( "change", ".unit_cost");
$(document.body).on('change', '.unit_cost', function(event)
{
var rowID = $(this).closest('tr').index();
alert(rowID);
var product_id = document.getElementsByName("product_id")[rowID].value;
alert('The product id is: ' + x);
var unit_cost = document.getElementsByName("unit_cost")[rowID].value;
});
Explanation:-
Since both inputs are in the same <td>, so on change of first-one you have to use .next() to get next input data.
You need to do it like below:-
$(document).on('change', '.unit_cost', function(event) {
var rowID = $(this).closest('tr').index();
alert(rowID);
var product_id = $(this).next('.product_id').val();
alert('The product id is: ' + product_id);
var unit_cost = $(this).val();
});
Working snippet:-
$(document).on('change', '.unit_cost', function(event) {
var rowID = $(this).closest('tr').index();
alert('The corresponding row index is: '+ rowID);
var product_id = $(this).next('.product_id').val();
alert('The product id is: ' + product_id);
var unit_cost = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td style='width:200px' class='left_align'>2 </td>
<td>3 </td>
<td> <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='4' /> <input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='5' type="hidden"/> </td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td style='width:200px' class='left_align'>9 </td>
<td>10 </td>
<td> <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='11' /><input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='12' type="hidden"/> </td>
<td>13</td>
<td>14</td>
</tr>
</table>

How to set name value of dynamic adding input ? javascript jquery

I have a web page for applying. In this web page, rows are dynamic add after addp button clicked.I can add new row successfully with addPf() method. And these input name attribute should be enName0, enName1, enName2....., but it works fail with name="enName"+aDWI.
Here is my html code:
<div>
<table>
<tr>
<td>
<input type="button" id="addP" onclick="addPf()" value="addPeople">
</td>
</tr>
<tr>
<td>
new row added in here;
</td>
</tr>
</table>
</div>
Here is my javascript code:
<script>
var aDWI=0;
function addPf()
{
newrow = '<tr><td><input style="width:98%" name="enName"+aDWI></td></tr>';
$(newrow).insertAfter($('#staTable tr:eq('+aDWI+')'));
aDWI = aDWI + 1;
}
</script>
name="enName"+aDWI is not right.I have no idea about this, who can help me ?
Change from
newrow = '<tr><td><input style="width:98%" name="enName"+aDWI></td></tr>';
to
newrow = '<tr><td><input style="width:98%" name="enName'+aDWI+'"></td></tr>';
The issue is because you need to concatenate the variable in the string correctly, using the ' character.
Also note that you should really be using unobtrusive event handlers instead of the outdated on* event attributes. In addition, you can simplify the logic by using jQuery's append(), like this:
var aDWI = 0;
$('#addP').click(function() {
newrow = '<tr><td><input style="width:98%" name="enName' + aDWI + '" value="' + aDWI + '"></td></tr>';
$('#staTable').append(newrow);
aDWI = aDWI + 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table id="staTable">
<tr>
<td>
<input type="button" id="addP" value="addPeople">
</td>
</tr>
<tr>
<td>
new row added in here;
</td>
</tr>
</table>
</div>
Just update it with
<script>
var aDWI=0;
function addPf()
{
newrow = '<tr><td><input style="width:98%" name="enName'+aDWI+'"></td></tr>';
$(newrow).insertAfter($('#staTable tr:eq('+aDWI+')'));
aDWI = aDWI + 1;
}
</script>

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/

Incrementing id attribute value through javascript

I am trying to dynamically add rows to a table to take orders and have created a javascript function for it.
function addnewrow()
{
var lastid = $("#table tr:last").attr("id");
var newid=lastid+1;
var newcolumn = document.createElement("tr");
newcolumn.id=newid;
newcolumn.innerHTML = "<td id='no"+newid+"'><a class='cut'>-</a>"+newid+"</td>"+
"<td>"+
"<ajaxToolkit:ComboBox ID='prod"+newid+"' runat='server' DataSourceID='SqlDataSource2' DataTextField='pname' DataValueField='pid' MaxLength='0' style='display: inline;'></ajaxToolkit:ComboBox>" +
"</td>"+
"<td><input type='number' required='required' min='1' name='quantity" + newid + "' /></td>" +
"<td id='price" + newid + "'></td>" +
"<td id='amount" + newid + "'></td>";
document.getElementById("table").appendChild(newcolumn);
}
I am doing this to get the values of all the elements in the code behind file to put them in database.
but due to this i get an error in the aspx.designer.cs page saying semicolon expected
protected global::AjaxControlToolkit.ComboBox prod" + newid + ";
ASP.NET Code
<table class="Grid" id="table">
<tr>
<td colspan="5">Enter Order Details</td>
</tr>
<tr>
<th>Sr No.</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
<tr id="1">
<td><a class="cut">-</a>1</td>
<td>
<ajaxToolkit:ComboBox ID="prod1" runat="server" DataSourceID="SqlDataSource2" DataTextField="pname" DataValueField="pid" MaxLength="0" style="display: inline;"></ajaxToolkit:ComboBox>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:micoConnectionString %>" SelectCommand="SELECT [pid], [pname] FROM [Products]"></asp:SqlDataSource>
</td>
<td><input type="number" required="required" min="1" name="quantity1" /></td>
<td id="price1"></td>
<td id="amount1"></td>
</tr>
</table>
<a class="add" onclick="addnewrow()" href="#">+</a>
Check this
$("#btnAddSchedule").click(function () {
var trs = $("[id^=trSchedules]");
var numberofrows = trs.length;
var newtr = $('#' + trs[0].id).clone();
$(newtr).attr('id', $(newtr).attr('id').replace(/\d+/, numberofrows));
newtr.find("input,select,img").each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, numberofrows));
$(this).attr('name', $(this).attr('name').replace(/\d+/, numberofrows));
if ($(this).attr('type') != "hidden") {
$(this).val('');
}
else if ($(this).attr('id').indexOf('DataExportQueueID') == -1) {
$(this).val('');
}
if ($(this).attr("type") == "checkbox") {
$(this).removeAttr("checked");
$(this).parent().html($(this).parent().html().replace(/\d+/g, numberofrows));
}
if ($(this).attr("type") == "button") {
$(this).attr("onclick", "deleteSchedule(this,0);");
}
});
$('#' + trs[numberofrows - 1].id).after(newtr);
CrossCheckScheduleRows();
});
function CrossCheckScheduleRows() {
$('[id^=trSchedules]').each(function () {
var row = $(this);
var index = row[0].rowIndex - 2;
row.attr('id', row.attr('id').replace(/\d+/, index));
row.find("input,select,img").each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, index)).attr('name', $(this).attr('name').replace(/\d+/, index));
});
});
}
I use this for the same purpose, maybe it will help you

Categories