how to assign names to new table columns cells dynamically - javascript

At the moment ,this code can create new columns dynamically.I would like to be able to give a unique name to all cells belonging to the mother column.NB:the mother column is the tallest of them all with three columns always.Any thing with less columns is a child.
SO all the cells and the contents in the first group must have a unique name identifer like say name="Bx_1name" to identify them from the next mother's contents(BX_2name);
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
}
item.appendChild(td);
});
}
</script>
Javascript is wellcome too.the functionality must not be changed.it must be just like this;
jsfiddle

Try this if it fits what you need.
JSFIDDLE
var counter =0;
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME['+counter+']" value="BX_NAME['+counter+']"/>';
counter++;
}
item.appendChild(td);
});
}
i used a global counter to increment each time a cell is made.

this is just a hint you can implement this as you want to achieve. First assign same class name for all your input fields
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text"/>
</td>
</tr>
</tbody>
</table>
then assign diffrent id's using jquery like following
<script type="text/javascript">
$(document).ready(function (event) {
var IDCount = 1;
$('.text').each(function () {
$(this).attr('id', IDCount);
IDCount++;
});
</script>
Hope this will help

Related

Update td content of a loaded tr

I tried several stuff I found now, but nothing seems to work for me.
On my site I got two tables. In one of them are entries with a button in the last column "add" which deletes the row from that table and moves it to the other table. When this happens I want to edit the content of that last <td>, so that there will be an "delete" button, which moves the entry back to the first table.
$("#questiontable").on('click', '.btnDelete', function () {
var question_id = $(this).val();
var tr = $(this).closest('tr').remove().clone();
tr[4].html("<button>delete</button>");
tr.appendTo("#currentquestiontable");
});
The td looks like this before:
<td>
<input type="hidden" name="id" value= {{question.id}} />
<button class="btnDelete">Hinzufügen</button>
</td>
You can set one click listener for both tables , and check by table id in order to transfer tr from table to another , same thing for text button ,(only change innerText button)
use listner for both table selectors :
$("#questiontable , #currentquestiontable").on('click', '.btnAction', function() {
var question_id = $(this).prev("input").val();
console.log(question_id)
let id = $(this).closest('table').attr("id");
var $tr = $(this).closest('tr').remove().clone();
let tableId= "";
let buttonText = "";
if(id === "questiontable") {
tableId= "#currentquestiontable";
buttonText = "remove";
}
else {
tableId= "#questiontable";
buttonText = "add";
}
$tr.find(".btnAction").text(buttonText);
$tr.appendTo(tableId);
});
See below example :
$("#questiontable , #currentquestiontable").on('click', '.btnAction', function() {
var question_id = $(this).prev("input").val();
console.log(question_id)
let id = $(this).closest('table').attr("id");
var $tr = $(this).closest('tr').remove().clone();
let tableId= "";
let buttonText = "";
if(id === "questiontable") {
tableId= "#currentquestiontable";
buttonText = "remove";
}
else {
tableId= "#questiontable";
buttonText = "add";
}
$tr.find(".btnAction").text(buttonText);
$tr.appendTo(tableId);
});
#currentquestiontable {
background-color:gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
table 1
<table id="currentquestiontable">
<tr>
<td>id</td>
<td>name</td>
<td>action</td>
</tr>
</table>
<hr>
<table id="questiontable">
<tr>
<td>id</td>
<td>name</td>
<td>action</td>
</tr>
<tr>
<td>1</td>
<td>elemnt n° 1</td>
<td>
<input type="hidden" name="id" value="1" />
<button class="btnAction">add</button>
</td>
</tr>
<tr>
<td>2</td>
<td>elemnt n° 2</td>
<td>
<input type="hidden" name="id" value="2" />
<button class="btnAction">add</button>
</td>
</tr>
<tr>
<td>3</td>
<td>elemnt n° 3</td>
<td>
<input type="hidden" name="id" value="3" />
<button class="btnAction">add</button>
</td>
</tr>
<tr>
<td>4</td>
<td>elemnt n° 4</td>
<td>
<input type="hidden" name="id" value="4" />
<button class="btnAction">add</button>
</td>
</tr>
<tr>
<td>5</td>
<td>elemnt n° 5</td>
<td>
<input type="hidden" name="id" value="5" />
<button class="btnAction">add</button>
</td>
</tr>
</table>

Using the same jQuery in multiple operations

I have a small question and I hope someone can help me with it :D
I’m trying to create a product table, in which a user just add the quantity of a product and the jquery makes the multiplication to its value and gives the result
I already made this, and it works well:
<script>
$(document).ready(function(){
$('#quantity_1').keyup(function(){
var price_1 = $("#price_1").val();
var quantity_1 = $("#quantity_1").val();
quantity_1 = quantity_1.replace(/[^0-9]+/g, '');
$("#quantity_1").val(quantity_1);
var total_1 = price_1 * quantity_1;
$( "#total_1" ).val( total_1.toFixed(2) );
});
});
</script>
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
</table>
Working demo here:
http://jsfiddle.net/EnterateNorte/9kswL0gf/
But I would like to be able to add more than one line, like so:
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Name 1</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
<tr>
<td>Name 5</td>
<td><input type="hidden" name="product[5][price]" id="price_5" value="10.00" />23.00</td>
<td><input type="text" name="product[5][quantity]" id="quantity_5" /></td>
<td><input type="text" name="product[5][total]" id="total_5" value="0" /></td>
</tr>
<tr>
<td>Name 3</td>
<td><input type="hidden" name="product[3][price]" id="price_3" value="130.00" />10.00</td>
<td><input type="text" name="product[3][quantity]" id="quantity_3" /></td>
<td><input type="text" name="product[3][total]" id="total_3" value="0" /></td>
</tr>
<tr>
<td>Name 4</td>
<td><input type="hidden" name="product[4][price]" id="price_4" value="12.00" />10.00</td>
<td><input type="text" name="product[4][quantity]" id="quantity_4" /></td>
<td><input type="text" name="product[4][total]" id="total_4" value="0" /></td>
</tr>
</table>
And if it isn’t to much trouble, I would be awesome if it would SUM all the totals and show a gran total at the end of the table :)
Use:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var price = $(this).parent().prev().find('input').val();
var quantity = $(this).val();
var total = price * quantity;
$(this).parent().next().find('input').val( total.toFixed(2) );
});});
Working Demo
Update: For showing Grand Total
var sum = 0;
//iterate through each textboxes and add the values
$('[name*=total]').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseInt(this.value);
}
});
Working Demo
What you can do is to find the elements using their relative position instead of hard coded ids
$(document).ready(function () {
$('input[id^="quantity_"]').keyup(function () {
var $tr = $(this).closest('tr');
var price = $tr.find('input[id^="price_"]').val();
var quantity = this.value;
var total = (price * quantity) || 0;
$tr.find('input[id^="total_"]').val(total.toFixed(2));
});
});
Demo: Fiddle
I've updated your code in Fiddle. You need to change in your markup a bit.
<tr>
<td>Product Name</td>
<td><input type="hidden" class="price" ... />10</td>
<td><input type="text" class="quantity" ... /></td>
<td><input type="text" class="total" ... /></td>
</tr>
$(document).ready(function(){
$('.quantity').keyup(function(){
var parent = $(this).closest("tr");
var price = $(".price", parent).val();
var quantity = $(".quantity", parent).val();
var total = price * quantity;
$(".total", parent).val(total.toFixed(2));
});
});
I would recommend you to use common class
HTML:
<tr>
<td>Name 5</td>
<td>
<input type="hidden" class="price" value="10.00" />10.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
<tr>
<td>Name 3</td>
<td>
<input type="hidden" class="price" value="130.00" />130.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
Script:
$('.quantity').keyup(function () {
var tr = $(this).closest('tr');
var price = tr.find('.price').val();
var quantity = $(this).val();
var total = price * quantity;
tr.find('.total').val(total.toFixed(2));
});
DEMO
Modify your table:
<table border="1" cellpadding="5px" cellspacing="0" id='table' >
<!-- your rows with inputs -->
<tr>
<td>
<input id='totalSum' value='0' type='text' />
</td>
</tr>
</table>
Make all your 'total' inputs readonly by adding 'readonly' attribute.
js code:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var total = 0;
$('#table tr').each(function(i,item){
var price = parseFloat($(item).find('[name*=price]').val().replace(',','.'));
var quantity = parseInt($(item).find('[name*=quantity]').val());
if(!isNaN(price) && !isNan(quantity)){
total += price*quantity;
}
});
$("#totalSum").val(total.toFixed(2));
});
});

How can I create a table dynamically?

I have made the table structure below. How can I add a second column of this table dynamically whenever I click add1 link using javascript? The whole column from up to down.This same column must be repeated again and again
Here is my HTML:
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add1
</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]">
</td>
</tr>
<tr>
<td>Add2
</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]">
</td>
</tr>
<tr>
<tdAdd3
</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]">
</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]">
</td>
</tr>
<tr>
<td>Add4
</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]">
</td>
</tr>
</tbody>
</table>
You need to bind a function to the link's click event. In that function, you need to iterate through each row, find the position where you want to add the column, and then insert it.
$(function(){
// bind the function to the click event
$("#add1").on("click", function(){
// iterate through each row
$("table tbody tr").each(function(){
// insert the column HTML at the desired point
$(this).children().first().after("<td>New Column</td>");
});
});
});
DEMO
If you want to make all of the links add the column when clicked, then just replace #add1 with .add in the jQuery.
I created a JavaScript function that adds a row to your table.
I also removed the <p> tag because it's not valid HTML and makes no visual difference.
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function addColumn(element) {
var tr = element.parentElement.parentElement;
var td = document.createElement("td");
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
tr.appendChild(td);
}
</script>
EDIT: Sorry, I misunderstood and thought you wanted to add a row. I changed the code to add a column instead.
EDIT 2: I changed the code so you can use it on multiple rows.

show/hide div based on radio button checked

I am trying to show/hide text fields based on checked radio buttons checked. Here is my code; it works fine if I don't use table tags, when using table tags, Javascript doesn't work
<script type="text/javascript">
function onchange_handler(obj, id) {
var other_id = (id == 'personal')? 'corporate' : 'personal';
if(obj.checked) {
document.getElementById(id + '_form_fields').style.display = 'block';
document.getElementById(other_id + '_form_fields').style.display = 'none';
} else {
document.getElementById(id + '_form_fields').style.display = 'none';
document.getElementById(other_id + '_form_fields').style.display = 'block';
}
}
</script>
<table>
<tr>
<td colspan="2">
<input type="radio" name="tipo_cadastro" value="individual_form" id="individual_form" style="margin:0px !important" onchange="onchange_handler(this, 'personal');" onmouseup="onchange_handler(this, 'personal');">
<strong>Individual Form</strong>
<input type="radio" name="tipo_cadastro" value="corporation_form" id="corporation_form" style="margin:0px !important" onchange="onchange_handler(this, 'corporate');" onmouseup="onchange_handler(this, 'corporate');">
<strong>Corporation Form</strong>
</td><tr>
<!-- If Individual Form is checked -->
<div id="personal_form_fields">
<tr><td>First Name</td>
<td><input type="text" name="First_Name" value=""></td>
</tr>
<tr><td>Last Name</td>
<td><input type="text" name="Last_Name" value=""></td>
</tr>
</div>
<!-- If Corporation Form is checked -->
<div id="corporate_form_fields" style="display: none;">
<tr><td>Company</td>
<td><input type="text" name="company_name" value=""></td>
</tr>
</div>
</table>
What putvande might mean by "strange markup" is that your <div id="personal_form_fields"> is in the table, with its parent being a table tag. That's not right. The tr should contain the td, which contains the div, not the other way around.
If you're trying to change visibility, this syntax error could be the problem.
Simply add a class to the TR of each group and show / hide the class...
<script type="text/javascript">
function onchange_handler(obj, id) {
var other_id = (id == 'personal')? 'corporate' : 'personal';
if(obj.checked)
{
class_display(id + '_form_fields','block');
class_display(other_id + '_form_fields','none');
} else {
class_display(id + '_form_fields','none');
class_display(other_id + '_form_fields','block');
}
}
function class_display(tr_class,display)
{
var tr_ele = document.getElementsByClassName(tr_class);
for (var i = 0; i < tr_ele.length; ++i) {
var item = tr_ele[i];
item.style.display = display;
}
}
</script>
<table>
<tr>
<td colspan="2">
<input type="radio" name="tipo_cadastro" value="individual_form" id="individual_form" style="margin:0px !important" onChange="onchange_handler(this, 'personal');" onmouseup="onchange_handler(this, 'personal');" checked>
<strong>Individual Form</strong>
<input type="radio" name="tipo_cadastro" value="corporation_form" id="corporation_form" style="margin:0px !important" onchange="onchange_handler(this, 'corporate');" onmouseup="onchange_handler(this, 'corporate');">
<strong>Corporation Form</strong>
</td>
<tr>
<!-- If Individual Form is checked -->
<tr class="personal_form_fields">
<td>First Name</td>
<td><input type="text" name="First_Name" value=""></td>
</tr>
<tr class="personal_form_fields">
<td>Last Name</td>
<td><input type="text" name="Last_Name" value=""></td>
</tr>
<!-- If Corporation Form is checked -->
<tr class="corporate_form_fields" style="display: none;">
<td>Company</td>
<td><input type="text" name="company_name" value=""></td>
</tr>
</table>

Javascript Add Table Row

I'm not sure how to add a row where I want it.
<script language="javascript">
var i = 1;
function changeIt()
{
i++;
my_div.innerHTML = my_div.innerHTML +"<tr><td valign='middle'><strong>URL "+ i+":</strong></td><td><input name='url'+ i type='text' size='40' /></td></tr>"
}
</script>
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<table width="300px">
<tr>
<td valign="middle"><strong>Name:</strong></td>
<td><input name="name" type="text" size="40" /></td>
</tr>
<tr>
<td valign="middle"><strong>Password:</strong></td>
<td><input name="password" type="text" size="40" /></td>
</tr>
<tr>
<td valign="middle"><strong>URL:</strong></td>
<td><input name="url" type="text" size="40" />+</td>
</tr>
<tr id="my_div"></tr>
<tr>
<td valign="middle"><strong>ETC:</strong></td>
<td><input name="etc" type="text" size="40" /></td>
</tr>
The following is where I want the rows to appear:
<tr id="my_div"></tr>
Currently that produces new rows within a row. I don't want that. I only want a new row not in a row.
When I click the + I want it to produce:
<tr>
<td valign="middle"><strong>URL 2:</strong></td>
<td><input name="url2" type="text" size="40" /></td>
</tr>
I don't want that within:
<tr id="my_div"></tr>
I just have that there because I don't know what to do.
Don't use innerHTML to modify tables, it will throw an error in most versions of IE. Use DOM methods.
Don't use an A element when you don't want an link or anchor, use an element like a button or styled span.
You can't add a TR element as a child of a DIV element, it's invalid. You must add it as a child of a table section element (thead, tbody or tfoot). In some cases you can add rows to a table element but some browsers don't like that either.
So to create the new row, use:
var tr = document.createElement('tr');
var td = tr.appendChild(document.createElement('td'));
// Much better to add a class and do this stuff with CSS
td.style.valign = 'middle';
var span = document.createElement('span');
span.style.fontWeight = 'bold';
span.appendChild(docment.createTextNode('URL ' + i);
td = tr.appendChild(document.createElement('td'));
var input = td.appendChild(document.createElement('input'));
input.name = 'url' + i;
input.type = 'text';
input.size = '40'
now append the TR to a table section somewhere.
document.getElementById('myTable').tBodies[0].appendChild(tr);
The whole thing looks like:
<script>
var i = 1;
function changeIt() {
var tr = document.createElement('tr');
var td = tr.appendChild(document.createElement('td'));
td.style.valign = 'middle';
var span = td.appendChild(document.createElement('span'));
span.style.fontWeight = 'bold';
span.appendChild(document.createTextNode('URL ' + i));
td = tr.appendChild(document.createElement('td'));
var input = td.appendChild(document.createElement('input'));
input.name = 'url' + ++i;
input.type = 'text';
input.size = '40'
document.getElementById('myTable').tBodies[0].appendChild(tr);
}
</script>
<form>
<table width="300px">
<tr>
<td valign="middle"><strong>Name:</strong></td>
<td><input name="name" type="text" size="40" /></td>
</tr>
<tr>
<td valign="middle"><strong>Password:</strong></td>
<td><input name="password" type="text" size="40" /></td>
</tr>
<tr>
<td valign="middle"><strong>URL:</strong></td>
<td><input name="url" type="text" size="40">
<input type="button" onclick="changeIt();" value="+"></td>
</tr>
<tr id="my_div"></tr>
<tr>
<td valign="middle"><strong>ETC:</strong></td>
<td><input name="etc" type="text" size="40" /></td>
</tr>
</table>
</form>
<table id="myTable">
<tbody></tbody>
</table>
You could build the row to add in the bottom table and have it hidden, then just clone it and modify the bits that need it.
Ok, so to add another row to the table after URL1, give the row before, URL1, an id attribute then append to the innerHTML. I set the JS to retrive the current URL number, starting with 1, so that each time you click the button, it appends a URL row.
I also updated your name attribute to include the '' ticks
<script language="javascript">
var i = 1;
function changeIt(){
var myCurrentTable = document.getElementById("myTable");
var txt = myCurrentTable.innerHTML;
i++;
txt = txt.replace('<tr id="etc_row">', '</tr><tr id="url_row_' + i + '"><td valign="middle"><strong>URL '+ i+':</strong></td><td><input name="url' + i + '" type="text" size="40" /></td><tr id="etc_row">');
myCurrentTable.innerHTML = txt;
}
</script>
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<table id="myTable" width="300px">
<tr id="name_row">
<td valign="middle"><strong>Name:</strong></td>
<td><input name="name" type="text" size="40" /></td>
</tr>
<tr id="pw_row">
<td valign="middle"><strong>Password:</strong></td>
<td><input name="password" type="text" size="40" /></td>
</tr>
<tr id="url_row_1" >
<td valign="middle"><strong>URL:</strong></td>
<td><input name="url" type="text" size="40" />+</td>
</tr>
<tr id="etc_row">
<td valign="middle"><strong>ETC:</strong></td>
<td><input name="etc" type="text" size="40" /></td>
</tr>
</table>

Categories

Resources