JQuery - can't delete table row - javascript

I don't know what is an error in this code. I have correctly detect parent. But doesn't work.
This is HTML code
<table>
<tbody class="tbody">
<tr id="row_1">
<td>
<input type="text" id="row_1_jumlah_1" name="row_1_jumlah_1" value="1" readonly="readonly" class="form-control" />
</td>
<td></td>
</tr>
<input type="button" class="btn green" value="Tambah Satuan" id="add_row" style="margin-bottom: 10px; margin-left:10px;" />
</tbody>
</table>
This is js code
$("#add_row").click(function () {
var last_index_tr = $(".tbody tr").length;
var new_index_tr = $(".tbody tr").length + 1;
var row = $("<tr id='row_" + new_index_tr + "'>");
var input = $("<td> <input class='form-control' type='text' id='row_" + new_index_tr + "_jumlah_1' name='row_" + new_index_tr + "_jumlah_1' value='1' readonly='readonly' /> </td>");
var action_delete = $("<td> <input class='btn btn-danger' type='button' id='row_" + new_index_tr + "_delete' class='delete' value='delete' /> </td>");
action_delete.click(function () {
var parent_1 = action_delete.parent();
var get_tr_parent_id = $(parent_1).attr('id');
//document.write(get_tr_parent_id);
$("#".get_tr_parent_id).remove();
});
row.append(input);
row.append(action_delete);
row.append("</tr>");
$(".tbody").append(row);
});
I want to remove tr inside table with delete button or action_delete(see js code). I have get parent perfectly. But I can't still delete tr.

Try this, You can use .on to hook the click handler for that delete button which is being created at runtime. Though your hooking is working, Using .on is a good practice while dealing with elements which are created dynamically. And by the way you have to concatenate the # with + Not with . That was the problem with your code, See your code working over here.
var action_delete = $("<td> <input class='btn btn-danger' type='button' id='row_" + new_index_tr +"_delete' class='delete' value='delete' /> </td>");
$(document).on('click',"#row_" + new_index_tr +"_delete",function(){
$(this).closest('tr').remove();
});
DEMO
Edit:
Try the following code, This will register to the click event commonly only once for your entire delete buttons.
$("#add_row").click(function () {
var last_index_tr = $(".tbody tr").length;
var new_index_tr = $(".tbody tr").length + 1;
var row = $("<tr id='row_" + new_index_tr + "'>");
var input = $("<td> <input class='form-control' type='text' id='row_" + new_index_tr + "_jumlah_1' name='row_" + new_index_tr + "_jumlah_1' value='1' readonly='readonly' /> </td>");
var action_delete = $("<td> <input class='btn btn-danger' type='button' id='row_" + new_index_tr + "_delete' class='delete' value='delete' /> </td>");
row.append(input);
row.append(action_delete);
row.append("</tr>");
$(".tbody").append(row);
});
$(document).on('click', "input[type='button'][id$='delete']",function(){
$(this).closest('tr').remove();
});
DEMO - I

Your remove method is incorrect. It should be:
$("#" + get_tr_parent_id).remove();
It was currently returning undefined instead of concatenating the two strings.

Related

vuejs creating onclick event from js method DOM

In my Vue CLI component, I'm populating a row table dynamically
i.e. inside my methods:
add_row() {
var new_name = document.getElementById("new_name").value;
var new_country = document.getElementById("new_country").value;
var new_age = document.getElementById("new_age").value;
var table = document.getElementById("data_table");
var table_len = table.rows.length - 1;
table.insertRow(table_len).outerHTML =
"<tr id='row" +
table_len +
"'><td id='name_row" +
table_len +
"'>" +
new_name +
"</td><td id='country_row" +
table_len +
"'>" +
new_country +
"</td><td id='age_row" +
table_len +
"'>" +
new_age +
"</td><td><input type='button' value='Delete' class='delete' #click=\"delete_row(" +
table_len +
')"></td></tr>';
document.getElementById("new_name").value = "";
document.getElementById("new_country").value = "";
document.getElementById("new_age").value = "";
}
This is the HTML part of the component:
<table
align="center"
cellspacing="2"
cellpadding="5"
id="data_table"
border="1"
>
<tr>
<th>Name</th>
<th>Country</th>
<th>Age</th>
</tr>
<tr id="row1">
<td id="name_row1">Ankit</td>
<td id="country_row1">India</td>
<td id="age_row1">20</td>
<td>
<input
type="button"
value="Delete"
class="delete"
#click="delete_row('1')"
/>
</td>
</tr>
<tr>
<td><input type="text" id="new_name" /></td>
<td><input type="text" id="new_country" /></td>
<td><input type="text" id="new_age" /></td>
<td>
<input
type="button"
class="add"
#click="add_row()"
value="Add Row"
/>
</td>
</tr>
</table>
Notice in my add_row function, when populating the row, I append a delete button tag and in it, pass the method delete_row. Clicking on this delete button should fire the method as shown below:
in my methods:
delete_row(no) {
document.getElementById("row" + no + "").outerHTML = "";
},
But the method is not being triggered from the delete_row function. I've confirmed that the rows are working well since my button for adding that row the add_row function fires. So my thinking is since I call the delete_row function from a dynamically created, there's perhaps something extra that I need to pass to my code to trigger this method?

How to set Javascript's variable value inside <input value=''">

I do not know how to formulate this question but it is near close to my issue. I am trying to make a Point of sale system so when client clicks in each product it adds in the table. There are no issues in my code but I do not know how to set the product's price using a textbox when using .append.
This is my code:
$(".agregarListaF").click(function (e) {
e.preventDefault();
var padre = $(this);
var hijos = padre.children().children("span");
var i = 0;
var datos = new Array();
hijos.each(function () {
switch (i) {
case 0:
datos[0] = $(this).text();
break;
case 1:
padre;
datos[1] = $(this).text();
break;
case 2:
padre;
datos[2] = $(this).text();
break;
}
i++;
});
console.log(datos[0]);
console.log(datos[1]);
$(".detallefactura").append(
"<tr>" +
"<td>" +
datos[0] +
"</td>" +
"<td>" +
datos[1] +
"</td>" +
"<td>" +
"<input type='text' class='form-control text-center' value='1'>" +
"</td>" +
"<td>" +
"<input type='text' class='form-control text-center' value=''>" +
"</td>" +
"<td class='tota-sub-fila'>" +
parseFloat(Math.floor(datos[2]) * parseFloat(1)).toFixed(2) +
"</td>"
);
});
My issue is in the line:
+ "<td>" + "<input type='text' class='form-control text-center' value=''>" + "</td>"
I want to add javascript value variable inside * input value=''* but I know It wont work but I tried it:
+ "<td>" + "<input type='text' class='form-control text-center' value='datos[2]'>" + "</td>"
This is my point of sale view:
In the column precio is where I want to set the price inside that textbox.
How do I solve this?
Please try this code,To How to set Javascript's variable value inside
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript| Set the value of an input field.
</title>
</head>
<body style="text-align:center;" id="body">
<input type='text' id='id1' />
<br>
<br>
<button onclick="gfg_Run()">
click to set
</button>
<p id="GFG_DOWN" style="color:green; font-size: 20px;font-weight: bold;"></p>
<script>
var el_down = document.getElementById("GFG_DOWN");
var inputF = document.getElementById("id1");
function gfg_Run() {
inputF.setAttribute('value', 'defaultValue');
el_down.innerHTML = "Value = " + "'" + inputF.value + "'";
}
</script>
</body>
</html>
I hope this information will be useful.
Thank you.
Follow this using template literals
const html = `<tr>
<td>${datos[0]}</td>
<td>${datos[1]}</td>
<td><input type="text" class="form-control text-center" value="${datos[3]}"></td>
<td><input type="text" class="form-control text-center" value="${datos[4]}"</td>
<td class="tota-sub-fila">${parseFloat((Math.floor(datos[2])) * parseFloat(1)).toFixed(2)}</td>
</tr>`;
$(.detallefactura").append(html);
You can do:
var variable="x";
"<input type='text' class='form-control text-center' value='"+ variable +"'>";
Or,
`<input type='text' class='form-control text-center' value='${variable}'>`
you can use Template literals like this instead of having this concatenation:
$(.detallefactura").append(`<tr>
<td> ${datos[0]} </td>
<td> ${datos[1]} </td>
<td> <input type='text' class='form-control text-center' value='1'> </td>
<td> <input type='text' class='form-control text-center' value='${datos[2]}'> </td>
<td class='tota-sub-fila'> ${parseFloat((Math.floor(datos[2])) * parseFloat(1)).toFixed(2)} </td>
`);

The event won't trigger when I use a variable for a selector

<html>
<body>
<h1>RECEIPT</h1>
<datalist id="codes">
<?php
require_once('../../../mysqli_connect.php');
$query = "SELECT DISTINCT itemcode FROM itemcost";
$response = #mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($response)){
echo '<option value="' . $row['itemcode'] . '">';
}
?>
</datalist>
<form action="receipt.php" method="POST">
<table cellspacing="10" id="tbl">
<thead>
<td>ITEM CODE:</td>
<td>ITEM NAME: </td>
<td>QUANTITY OF ITEM:</td>
</thead>
<tbody>
<tr>
<td><input type="text" list="codes" name="Item_Code1" id="setter" size="5" /></td>
<td><input type="text" name="Item_Name1" id="receiver" size="10" /></td>
<td><input type="text" name="Quantity_In1" size="5" /></td>
</tr>
</tbody>
</table>
<br>
<br>
<input type="number" name="rows" id="addrows" />
<button type="button" id="btn">Add More</button>
<input type="submit" name="submitted" value="Enter" />
<input type="text" name="sendtotalrows" id="totalrows" style="visibility:hidden"/>
</form>
<script src="jquery.js"></script>
<script>
$(function(){
window.rowcompare = 2;
window.previousrownumber = 1;
$('#setter').change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $('#setter').val();
$('#receiver').val(itemcodename[selectedItemCode]);});});
$('#btn').on('click', function(){
var rownumber = $('#addrows').val();
rownumber = parseInt(rownumber) + window.previousrownumber;
while( rownumber >= rowcompare){
$('#tbl').find('tbody').append("<tr><td><input type=\"text\" list=\"codes\" name=\"Item_Code" + rowcompare +"\" id=\"setter" + rowcompare +"\" size=\"5\" /></td><td><input type=\"text\" name=\"Item_Name" + rowcompare +"\" id=\"receiver" + rowcompare +"\" size=\"10\" /></td><td><input type=\"text\" name=\"Quantity_In" + rowcompare +"\" size=\"5\" /></td></tr>");
$("#setter" + rowcompare).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + rowcompare).val();
$("#receiver" + rowcompare).val(itemcodename[selectedItemCode]);});});
rowcompare++;
}
previousrownumber = rownumber;
$('#totalrows').val(previousrownumber);
});
});
</script>
</body>
</html>
My problem lies in this part of the code inside the while loop where I try to concatenate a variable to the Selector.
getitemcode.php just returns a key-value pair
$("#setter" + rowcompare).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + rowcompare).val();
$("#receiver" + rowcompare).val(itemcodename[selectedItemCode]);
});
});
As the title says, my event won't trigger. I've seen similar questions asked and below are the answers I've tried:
var IcodeID = 'setter' + toString(rowcompare)
var InameID = 'receiver' + toString(rowcompare)
$("#" + IcodeID ).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#" + IcodeID ).val();
$("#" + InameID ).val(itemcodename[selectedItemCode]);
});
});
parseInt(rowcompare);
$("#setter" + ${rowcompare}).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + ${rowcompare}).val();
$("#receiver" + ${rowcompare}).val(itemcodename[selectedItemCode]);
});
});
parseInt(rowcompare);
$("#setter" + rowcompare).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + rowcompare).val();
$("#receiver" + rowcompare).val(itemcodename[selectedItemCode]);
});
});
But the thing is when I try this:
$("#setter" + 2).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + 2).val();
$("#receiver" + 2).val(itemcodename[selectedItemCode]);
});
});
It works. Any help would be appreciated.
I got the solution from this link:
Passing variable to :eq jquery selector in a while loop
You need to wrap the Jquery code that uses the incremented variable inside this:
(function(rowcompare){ Jquery Code })(rowcompare);
Like so:
(function(rowcompare){
$(".code-input" + rowcompare).change(function(){ $.getJSON('getitemcodename.php', function(itemcodenamestocks) {
var selectedItemCode = $(".code-input" + rowcompare).val();
$(".code-output" + rowcompare).val(itemcodenamestocks[0][selectedItemCode]);
$(".stocks-output" + rowcompare).val(itemcodenamestocks[1][selectedItemCode]);
});
});
})(rowcompare);
And it works.

Add a blank row in HTML Table

I have an HTML table that adds a new row below where the button in current row is located. Currently when the row is created it generates a clone of the row above including the data. I would like this to be a row that has no entry for the input values rather than a clone of the values above.
Javascript
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
}
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
after you add a row, you can just set the values of all inputs in that row to "". get all the inputs of type text using tr.querySelectorAll("input[type='text']") and using a loop set values of all to ""
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for(var i=0; i<inputs.length; i++)
inputs[i].value = "";
}
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
You can do this very easily with jQuery:
var $lastRow = $("table#Table tr:last-child");
var $newRow = $lastRow.clone()
$newRow.find("input[type=text]").val(''); //empty all the values in text inputs
$("table#Table").append( $newRow );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
Add this line of code to your function to empty values in HTML code:
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
tr.innerHTML = tr.innerHTML.replace(/value='.*'/, "value=''"); //this will remove all values from your html
tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
}
Using JQuery:
function addRow(){
var t = $("#Table tr").last().clone();
t.find("input").each(function(i,element) {
$(element).val("");
});
t.appendTo("#Table");
}
I can suggest you do this - define table rows in javascript and add those directly. Also, use th for table headers
function edit_row(no) {
document.getElementById("edit_button" + no).style.display = "none";
document.getElementById("save_button" + no).style.display = "block";
// get elements
var measured = document.getElementById("measured_row" + no);
var inclination = document.getElementById("inclination_row" + no);
var azimuth = document.getElementById("azimuth_row" + no);
// get their values
var measured_data = measured.innerHTML;
var inclination_data = inclination.innerHTML;
var azimuth_data = azimuth.innerHTML;
// replace by editable input tags
measured.innerHTML = "<input type='text' id='measured_text" + no + "' value='" + measured_data + "'>";
inclination.innerHTML = "<input type='text' id='inclination_text" + no + "' value='" + inclination_data + "'>";
azimuth.innerHTML = "<input type='text' id='azimuth_text" + no + "' value='" + azimuth_data + "'>";
}
function save_row(no) {
// same as in edit function
var measured_val = document.getElementById("measured_text" + no).value;
var inclination_val = document.getElementById("inclination_text" + no).value;
var azimuth_val = document.getElementById("azimuth_text" + no).value;
document.getElementById("measured_row" + no).innerHTML = measured_val;
document.getElementById("inclination_row" + no).innerHTML = inclination_val;
document.getElementById("azimuth_row" + no).innerHTML = azimuth_val;
document.getElementById("edit_button" + no).style.display = "block";
document.getElementById("save_button" + no).style.display = "none";
}
function delete_row(no) {
document.getElementById("row" + no + "").outerHTML = "";
}
function add_row() {
var new_measured = document.getElementById("new_measured").value;
var new_inclination = document.getElementById("new_inclination").value;
var new_azimuth = document.getElementById("new_azimuth").value;
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='measured_row" + table_len + "'>" + new_measured + "</td><td id='inclination_row" + table_len + "'>" + new_inclination + "</td><td id='azimuth_row" + table_len + "'>" + new_azimuth + "</td><td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'> <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> <input type='button' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_measured").value = "";
document.getElementById("new_inclination").value = "";
document.getElementById("new_azimuth").value = "";
}
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<tr>
<th>Measured Depth</th>
<th>Inclination</th>
<th>Azimuth</th>
</tr>
<tr id="row1">
<td id="measured_row1">339</td>
<td id="inclination_row1">0.540000021</td>
<td id="azimuth_row1">310.7200012</td>
<td>
<input type="button" id="edit_button1" value="Edit" class="edit" onclick="edit_row('1')">
<input type="button" id="save_button1" value="Save" class="save" onclick="save_row('1')">
<input type="button" value="Delete" class="delete" onclick="delete_row('1')">
</td>
</tr>
<tr>
<td><input type="text" id="new_measured"></td>
<td><input type="text" id="new_inclination"></td>
<td><input type="text" id="new_azimuth"></td>
<td><input type="button" class="add" onclick="add_row();" value="Add Row"></td>
</tr>
</table>

How to use select option jquery function

I am not a UI developer, But I am doing R&D on javascript, I have written a code where each row is getting added, But I want to add a select option in a newly created row.
Below is the code
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("</td><td><input name='name"+i+"' type='text' placeholder='FIELD' class='form-control input-md' /> </td> <select name='TYPE' ><option value='ORANGE'>ORANGE</option><option value='YELLOW'>YELLOW</option><option value='GREEN'>GREEN</option></select> <td class='deleterow'><div class='glyphicon glyphicon-remove'></div></td></tr>")});
Can we modify this , I want to get Select tag when I call #add_row function each time
I could not get clearly what you want. But I have created a fiddle for you.
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr').append("<tr><td><input name='name"+i+"' type='text' placeholder='FIELD' class='form-control input-md' /> </td><td> <select name='TYPE' ><option value='ORANGE'>ORANGE</option><option value='YELLOW'>YELLOW</option><option value='GREEN'>GREEN</option></select> <td class='deleterow'><div class='glyphicon glyphicon-remove'></div></td></tr>")
i++;
});
});
HTML will be like
<button id="add_row">Add row</button>
<table id="addr"></table>
I suggest you to separate you HTML in the event callback to handle easily each column and it's data.
I'm using in my example jQuery's Append and Selectors features.
Working example, take a look:
// Waiti the DOM LOAD
$(document).ready(function(){
// Setting the first row ID as 1
var row_ID = 1;
// Handle the button click event
$("#add_row").click(function(){
// Setting some templates to separate yout HTMLs
var col_1_template = "<td><input name='name" + row_ID + "' type='text' placeholder='FIELD' class='form-control input-md' /></td>";
var col_2_template = "<td><select name='TYPE" + row_ID + "' ><option value='ORANGE'>ORANGE</option><option value='YELLOW'>YELLOW</option><option value='GREEN'>GREEN</option></select> <td class='deleterow'><div class='glyphicon glyphicon-remove'></div></td>";
// Insertint an empty line
$('#your_table_ID').append("<tr></tr>");
// Get the new line
var actual_line = $('#your_table_ID tr:last');
// Appending each column
actual_line.append(col_1_template)
actual_line.append(col_2_template);
// Rows count
row_ID++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add_row">+</button>
<table id="your_table_ID"></table>
jQuery's Selectors official documentation:
https://api.jquery.com/category/selectors/
And jQuery's Append:
http://api.jquery.com/append/
Hope it helps
Here's what I've done for you.
$(document).ready(function(){
$("#add_row").click(function(){
var totalRows = $('.row').length, nextI = totalRows + 1;
$('.rowContainer').append("<tr class='row'><td><input name='name_" +nextI+ "' type='text' placeholder='FIELD' class='form-control input-md' /><select name='TYPE'><option value='ORANGE'>ORANGE</option><option value='YELLOW'>YELLOW</option><option value='GREEN'>GREEN</option></select></td><td class='deleterow'><div class='glyphicon glyphicon-remove'>X</div></td></tr>");
});
$(document).on('click', ".glyphicon-remove", function() {
$(this).closest('.row').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add_row">Add row !</button>
<table class="rowContainer"></table>

Categories