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>
Related
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>
I am trying to clone and append a table row when the user selects my add rows button. I have an empty hidden row that is used to clone. I can't seem to get it to work how I need it too.
I output my form with PHP and looks something like this:
$budgetRowCount = 0;
echo"<table id='selected_budget_table'>
<tr>
<th>Roofs</th>
<th>Roof Area</th>
<th>Recommendations</th>
<th>Amount</th>
<th>Remove</th>
</tr>";
echo "<tr id='new_budget_row0' style='display: none;'>
<td><input id='budget-roofs' name='budget-roofs[]' /></td>
<td><input id='budget-area' name='budget-area[]' /></td>
<td><input id='budget-recommendation' name='budget-recommendations[]' /></td>
<td><input id='budget-amount' name='budget-amount[]'/> </td>
</tr>";
while ($budgetInfoRow = mysqli_fetch_array($budgetResult)) {
if($budgetRowCount == 0){
echo "<tr id='selected_budget_row". $budgetRowCount ."'>";
echo "<td><input type='text' id='budget-roofs' name='budget-roofs[]' value='".$budgetInfoRow['budget_roofs']."'</td>";
echo "<td><input type='text' id='budget-roof-area' name='budget-roof-area[]' value='".$budgetInfoRow['budget_roof_area']."'</td>";
echo "<td><input type='text' id='budget-recommendation' name='budget-recommendation[]' value='".$budgetInfoRow['budget_recommendation']."'</td>";
echo "<td><input type='text' id='budget-amount' name='budget-amount[]' value='".$budgetInfoRow['budget_amount']."'</td>";
echo "</tr>";
$budgetRowCount++;
}
else{
echo "<tr id='selected_budget_row". $budgetRowCount ."'>";
echo "<td><input type='text' id='budget-roofs' name='budget-roofs[]' value='".$budgetInfoRow['budget_roofs']."'</td>";
echo "<td><input type='text' id='budget-roof-area' name='budget-roof-area[]' value='".$budgetInfoRow['budget_roof_area']."'</td>";
echo "<td><input type='text' id='budget-recommendation' name='budget-recommendation[]' value='".$budgetInfoRow['budget_recommendation']."'</td>";
echo "<td><input type='text' id='budget-amount' name='budget-amount[]' value='".$budgetInfoRow['budget_amount']."'</td>";
echo "<td><a href='#' class='removeRow' data-remove-row='budget_row". $budgetRowCount . "'>Remove</a></td>";
echo "</tr>";
$budgetRowCount++;
}
}
echo "</table>";
echo"<input type='button' value='+' id='addNewBudgetRow' class='addNewBudgetRow'/>";
And this is how I am attempting to clone my row and add it to my table:
$(function() {
var $removeIDVal = 0;
$(document.body).on('click', '.addNewBudgetRow', function () {
var $emptyBudgetTableRow = $("#new_budget_row0").clone();
$removeIDVal++
var $emptyBudgetTableRowClone = $emptyBudgetTableRow.clone();
var $newRowID = 'added_budget_row' + $removeIDVal;
$emptyBudgetTableRowClone.attr('id', $newRowID)
$emptyBudgetTableRowClone.children('td').last().after('<td>Remove</td>');
$(this).closest("fieldset").find("tbody").append($emptyBudgetTableRowClone);
$emptyBudgetTableRowClone.show();
});
});
I had an alert to check if the button was actually firing and my alert showed up no problem, however I can't seem to get it to clone and append properly and I have done this several times elsewhere with no issues. Where am I going wrong here?
How can I fix this so that my row gets cloned properly and added to the end of my table?
You are not selecting your table, since you have no <fieldset> or <tbody>. Select it by id.
Alos you were cloning new row twice and you have multiple same ids.
$(document.body).on('click', '.addNewBudgetRow', function () {
var $emptyBudgetTableRowClone = $("#new_budget_row0").clone();
$removeIDVal++
var $newRowID = 'added_budget_row' + $removeIDVal;
$emptyBudgetTableRowClone.attr('id', $newRowID)
$emptyBudgetTableRowClone.children('td').last().after('<td>Remove</td>');
$('#selected_budget_table').append($emptyBudgetTableRowClone);
$emptyBudgetTableRowClone.show();
});
});
$(function() {
var $removeIDVal = 0;
$(document.body).on('click', '.addNewBudgetRow', function () {
var $emptyBudgetTableRowClone = $("#new_budget_row0").clone();
$removeIDVal++
var $newRowID = 'added_budget_row' + $removeIDVal;
$emptyBudgetTableRowClone.attr('id', $newRowID)
$emptyBudgetTableRowClone.children('td').last().after('<td>Remove</td>');
// Select you table by id
$('#selected_budget_table').append($emptyBudgetTableRowClone);
$emptyBudgetTableRowClone.show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='selected_budget_table'>
<tr>
<th>Roofs</th>
<th>Roof Area</th>
<th>Recommendations</th>
<th>Amount</th>
<th>Remove</th>
</tr>
<tr id='new_budget_row0' style='display: none;'>
<td><input id='budget-roofs' name='budget-roofs[]' /></td>
<td><input id='budget-area' name='budget-area[]' /></td>
<td><input id='budget-recommendation' name='budget-recommendations[]' /></td>
<td><input id='budget-amount' name='budget-amount[]'/> </td>
</tr>
</table>
<input type='button' value='+' id='addNewBudgetRow' class='addNewBudgetRow'/>
I've put it up on jsFiddle and found + fixed some issues:
http://jsfiddle.net/lumpie/nprsdb2m/
$(function() {
var $removeIDVal = 0;
$(document.body).on('click', '.addNewBudgetRow', function () {
var $emptyBudgetTableRow = $("#new_budget_row0");
$removeIDVal++
var $emptyBudgetTableRowClone = $emptyBudgetTableRow.clone();
var $newRowID = 'added_budget_row' + $removeIDVal;
$emptyBudgetTableRowClone.attr('id', $newRowID)
$emptyBudgetTableRowClone.append('<td>Remove</td>');
$("#selected_budget_table").append($emptyBudgetTableRowClone);
// Logic to remove a row:
$emptyBudgetTableRowClone.find(".removeRow").click(function() {
$(this).parents("tr").remove();
});
$emptyBudgetTableRowClone.show();
});
});
Ah, just a minute too late, Rene Korss was slightly ahead of me.
But hey: I've included a little extra: logic to make the Remove button work :)
I know this a basic question but I don't know what to do. I have been stuck on this from hours but I don't know what is wrong with it.
what I want to do:
I want to append input field when user click on button(simple!).
Problem: It only append one time only.
This is my fiddle
Html code:
<table class="table table-bordered" id="tab_logic">
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center">Name</th>
<th class="text-center">Quantity</th>
</tr>
</thead>
<tbody>
<tr id='addr0'></tr>
</tbody>
</table>
<button id='add' class="btn btn-outline btn-default">Add</button>
Jquery code:
var i=0;
$('#add').click( function() {
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
$('#addr'+(i+1)).html("<td>"+ (i+1) +"</td>"+
"<td><input type='text' class='form-control input-md' /></td>"+
"<td><input type='text' class='form-control input-md'></td>"+
"<td><a class='btn btn-default glyphicon glyphicon-remove' onclick='deleterow(this)' class'delete'></a></td>"
);
});
function deleterow(obj){
$(obj).parent().parent().remove();
return false;
}
Sorry I know Its very basic question but my JavaScript is weak.
You forgot to increment variable i:
i++
https://jsfiddle.net/pUeue/1781/
https://jsfiddle.net/pUeue/1777/
var i=0;
$('#add').click( function() {
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
$('#addr'+(i+1)).html("<td>"+ (i+1) +"</td>"+
"<td><input type='text' class='form-control input-md' /></td>"+
"<td><input type='text' class='form-control input-md'></td>"+
"<td><a class='btn btn-default glyphicon glyphicon-remove' onclick='deleterow(this)' class'delete'></a></td>");
i++;
});
You don't increment i after you click
everytime i value is 0 and i+1 is always 1. add i=i+1; to your code.
Please find below code
$('#add').click( function() {debugger;
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
$('#addr'+(i+1)).html("<td>"+ (i+1) +"</td>"+
"<td><input type='text' class='form-control input-md' /></td>"+
"<td><input type='text' class='form-control input-md'></td>"+
"<td><a class='btn btn-default glyphicon glyphicon-remove' onclick='deleterow(this)' class'delete'></a></td>"
);
i=i+1;
});
Change your javascript a little bit to work:
var i=0;
$('#add').click( function() {
i += 1;
$('#tab_logic').append('<tr id="addr'+(i)+'"></tr>');
$('#addr'+(i)).html("<td>"+ (i) +"</td>"+
"<td><input type='text' class='form-control input-md' /></td>"+
"<td><input type='text' class='form-control input-md'></td>"+
"<td><a class='btn btn-default glyphicon glyphicon-remove' onclick='deleterow(this)' class'delete'></a></td>"
);
});
function deleterow(obj){
$(obj).parent().parent().remove();
return false;
}
variable i is defined as global variable, while in your method, you are not increasing its value. That was the issue.
Here is the update fiddle:
https://jsfiddle.net/pUeue/1784/
I realise there are already 4 answers, but I would like to demonstrate the tips I mentioned in comment for creating simple code that is easier to maintain.
Also your HTML concatenation is actually not quite right, but nobody can tell with all the string operations.
Use the existing row count (or last id) etc to determine the next id number to generate.
Consider using a dummy/template element instead of HTML string concatenation. This allows for maintainable templates.
Use single quotes for the outer strings, that that the HTML attributes have double-quotes (for browser compatibility).
This example has the first two as the quotes issue goes away:
JSFiddle: https://jsfiddle.net/pUeue/1787/
$('#add').click(function () {
var count = $('#tab_logic tr').length;
$('#tab_logic').append($('#template').html().replace(/{i}/g, count));
});
function deleterow(obj) {
$(obj).parent().parent().remove();
return false;
}
In this example your template row sits in a dummy script block (of unknown type so is ignored). It uses a "global" replace option in a regex to replace all occurrences of a placeholder with the desired value(s).
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.
function CreateInterface(){
document.getElementById("welcome").innerHTML=
'<form action="?" method="get" onsubmit=" return validate(this)">' +
'<table id="dataTable" summary="" cellspacing="3" cellpadding="0" border="0">' +
'<tr id="tablerow">' + '<td><INPUT type="checkbox" name="chk"/></td> '+
'<th>Userid : </th>' + '<td ><input name="userid" type="text" class="text" value="" maxlength="10" /></td>' +
'</tr>' + '<tr><td colspan="2" align="center">'+
'<INPUT type="button" value="Add" onclick="addRow()" />' +
'<INPUT type="button" value="Delete" onclick="delRow()" />' +
'<input type="submit" value="submit" />'+'</td></tr>' +
'</table>' +
'</form>';
}
function addRow(){
var clnNode=document.getElementById("tablerow").cloneNode(true);
document.getElementById("dataTable").appendChild(clnNode);
}
This is my code , i want this cloned node to be inserted above the buttons. In fact this code is not working, i.e. node is not getting added to table. Please help me solve this
Do not use id="tablerow" as duplicate ids will cause malformed HTML.
Change <tr id="tablerow"> in your string to just <tr>
Script
function addRow() {
var referenceNodes = document.getElementById("dataTable").getElementsByTagName("tr");
//-2 because last row is button row
var referenceNode = referenceNodes[referenceNodes.length - 2];
var newNode = referenceNode.cloneNode(true);
newNode.getElementsByTagName("input")[0].checked = false;
newNode.getElementsByTagName("input")[1].value = "";
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
Demo: http://jsfiddle.net/naveen/wbFMm/
You need to use insertBefore and pass lastChild as second parameter to insert the cloned row just above buttons.
function addRow(){
var table=document.getElementById("dataTable")
var clnNode=document.getElementById("tablerow").cloneNode(true);
table.insertBefore(clnNode,table.lastChild);
}
Here is working example: http://jsfiddle.net/amantur/8KYum/10/
As for code is not working, you are not calling CreateInterface from anywhere. Set it up to run on onLoad and things will work.
Your problem is your using the same ID for several elements (tableRow). An id must be unique on an html page. As seen in here.
A better solution would be to have only one row with the ID and every time you clone the row simply remove the id from the clone.
try the below code. I've just tweaked your existing addRow function
function addRow(){
var clnNode=document.getElementById("tablerow").cloneNode(true);
tableObj = document.getElementById("dataTable");
tbodyObj = document.getElementById("dataTable").getElementsByTagName('tbody')[0]
tableObj.insertBefore(clnNode, tbodyObj)
}