How i find dynamic id of dynamic table through jquery? - javascript

I am facing some issues related to creating an dynamic table. I append rows through jquery on onchange event . My issue is i want to find row Index of each rows in table how can i get this id using jquery?
Any body who can help me?
This is my code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="assets/js/libs/jquery-3.5.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
</head>
<body>
<button id="btn" onclick="addRow()">Add Row</button>
<table id="Items_table" border="1">
<thead>
<tr>
<th>Item Name</th>
<th colspan="2">Quantity</th>
<th>Purchase Price</th>
<th>Tax%</th>
<th>Tax Amount</th>
<th>Discount</th>
<th>Unit Cost</th>
<th>Total Amount</th>
<th>Action</th>
</tr>
</thead>
<tbody id="Item_table_data">
</tbody>
</table>
<script>
var numberofRowsforItems = 0;
function addRow() {
numberofRowsforItems++;
var htmlforItemTable = '<tr class="" id=" " data-row="1"><td class="tablerow"><span style="color:White">Hello</span></td ><td colspan="2"> <div><button id="table_q_btn">-</button> <input type="text"/><button id="table_q_btn">+</button> </div> </td >'
+ '<td><input type="text" value="Hellos" id="HelloID"/></td><td><input type="text" value="Hello" disabled/></td>'
+ '<td><input type="text" value="Hello"/></td><td><input type="text"/></td><td><span style="color:White">Hasd</span></td><td><span style="color:White">qdasd</span></td><td><button class="remove">-</button><button class="getId">Id</button></td></tr >';
$('#Item_table_data').append(htmlforItemTable);
}
$(document).on('click', '.getId', function () {
var a = $(this).closest('tr').find('.tablerow').val();
alert(a);
var b = $(this).val();
alert(b);
});
$(document).on('click', '.remove', function () {
$(this).parents('tr').remove();
});
</script>
</body>
</html>
I want to append this dynamic row in table and now i want to get every row index through jquery or javascript

Here's what the code should look like:
var numberofRowsforItems = 0;
function addRow() {
numberofRowsforItems++;
var htmlforItemTable = '<tr class="" id="'+ numberofRowsforItems +'" data-row="1"><td class="tablerow"><span style="color:White">Hello</span></td ><td colspan="2"> <div><button id="table_q_btn">-</button> <input type="text"/><button id="table_q_btn">+</button> </div> </td >'
+ '<td><input type="text" value="Hellos" id="HelloID"/></td><td><input type="text" value="Hello" disabled/></td>'
+ '<td><input type="text" value="Hello"/></td><td><input type="text"/></td><td><span style="color:White">Hasd</span></td><td><span style="color:White">qdasd</span></td><td><button class="remove">-</button><button class="getId">Id</button></td></tr >';
$('#Item_table_data').append(htmlforItemTable);
}
$(document).on('click', '.getId', function () {
var a = $(this).closest('tr').attr('id');
alert(a);
});
What I've changed is: id="'+ numberofRowsforItems +'" and: $(this).closest('tr').attr('id');

Related

How to copy the value from one input box to another input box?

By clicking on Add New Row button, new input boxes can be generated. I want to copy the value from one input box (First column - Hours ) to another input box (Second Column - In Office).
Screenshot:
First Row: Value is copied from one input box to another input box when it is a static element. Here input box is created by HTML.
Dynamic Rows: Value is not copied from one input box to another input box when it is a dynamic element. Here input box is created by JavaScript.
Issue:
Value is not copied because the elements are generated dynamically with same id and name
What I tried:
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
// Append table with add row form on add new button click
$(".add_new").click(function() {
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="number" name="hours[]" id="hours"></td>' +
'<td><input type="number" name="inoffice[]" id="inoffice"></td>' +
'</tr>';
$("table").append(row);
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function() {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function() {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function() {
$(this).parent("td").html($(this).val());
});
}
});
});
function sync() {
var hours = document.getElementById('hours');
var inoffice = document.getElementById('inoffice');
inoffice.value = hours.value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th>Hours</th>
<th>In Office</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="hours[]" id="hours" onkeyup="sync()" onClick="sync()"></td>
<td><input type="number" name="inoffice[]" id="inoffice"></td>
</tr>
</tbody>
</table>
<input type="button" id="add_new" name="add_new" class="add_new" value="Add New Row">
You should not be duplicating id attributes as it's invalid HTML and will lead to other issues. Use class attributes instead to group elements by common behaviour patterns.
From there you can use a delegated event handler to handle all the .hours elements that will ever exist in the DOM.
Also note that inline event attributes are outdated and should be avoided where possible.
$('table').on('input', '.hours', function() {
$(this).closest('tr').find('.inoffice').val(this.value);
});
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
$(".add_new").click(function() {
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="number" name="hours[]" class="hours"></td>' +
'<td><input type="number" name="inoffice[]" class="inoffice"></td>' +
'</tr>';
$("table").append(row);
$('[data-toggle="tooltip"]').tooltip();
});
$(document).on("click", ".add", function() {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function() {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function() {
$(this).parent("td").html($(this).val());
});
}
});
$('table').on('input', '.hours', function() {
$(this).closest('tr').find('.inoffice').val(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th>Hours</th>
<th>In Office</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="hours[]" class="hours"></td>
<td><input type="number" name="inoffice[]" class="inoffice"></td>
</tr>
</tbody>
</table>
<input type="button" id="add_new" name="add_new" class="add_new" value="Add New Row">
Start by creating an MCVE. That means remove all the code that isn't part of the problem. This will make everything clearer.
Remove IDs, since IDs must be unique, we better use classes instead.
$(document).ready(function() {
$(".add_new").click(function() {
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="number" name="hours[]" class="hours"></td>' +
'<td><input type="number" name="inoffice[]" class="inoffice"></td>' +
'</tr>';
$("table").append(row);
$('[data-toggle="tooltip"]').tooltip();
});
});
$(document).on("keyup", ".hours", function(){
$(this).parent().parent().find(".inoffice").val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th>Hours</th>
<th>In Office</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="hours[]" class="hours"></td>
<td><input type="number" name="inoffice[]" class="inoffice"></td>
</tr>
</tbody>
</table>
<input type="button" id="add_new" name="add_new" class="add_new" value="Add New Row">

How to add and remove <tr> to table based on checkbox selection in jQuery

I'm trying to create a users' permission table which will display the type of permission to assign a user, based on a selection from a checkbox.
I have tried several means I know about and also searched but I always seem to get stuck everytime.
I got a similar code from this answer, jQuery append and remove values from checkbox to textarea , which works. But when I try implementing it in my work, it doesn't seem to work.
<table id="permissionsTable">
<thead>
<th>Name</th>
<th>Slug</th>
<th>Description</th>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<div id="alloptions">
<ul>
<li>
<input type="checkbox" name="option1" value="Play" />Play</li>
<li>
<input type="checkbox" name="option1" value="Create" />Create</li>
<li>
<input type="checkbox" name="option1" value="Delete" />Delete</li>
</ul>
</div>
And here's the jQuery Code:
var checkboxes = $("input[type='checkbox']");
var permsTable = $("#permissionsTable");
var valuer = [];
checkboxes.on('change', function() {
var values = checkboxes.filter(':checked').map(function(x, y) {
return y.value;
}).get();
checkboxes.filter(':checked').each(function(a, b) {
valuer.push($(this).val());
});
if (checkboxes.is(':checked')) {
permsTable.find('tbody').detach();
permsTable.append($('<tbody>'));
$.each(valuer, function(c, d) {
//alert(x + " : " + y);
var nameCol = d.substr(0, 1).toUpperCase() + d.substr(1) + " " + "Game";
var slugCol = d.toLowerCase() + "-" + "Game";
var descriptionCol = "Allow user to " + d.toUpperCase() + " a " + "Game";
$("#permissionsTable").find('tbody').append("<tr><td>" + nameCol + "</td><td>" + slugCol + "</td><td>" + descriptionCol + "</td></tr>");
});
} else {
permsTable.find('tbody').detach();
permsTable.append($('<tbody>'));
btnGeneratePermissions.css("display", "none");
}
});
I expect to add the values of the checkboxes to the table row when checkbox is checked; and then remove the row upon uncheck.
Using a Template Literal, this is pretty easy
$("#alloptions").on("change", "[name=option1]", function(){
var mode = $(this).val();
const rowTemp = `<tr data-mode=${mode}>
<td><span style="text-transform: capitalize;">${mode} Game</span></td>
<td><span style="text-transform: lowercase;">${mode}</span>-Game</td>
<td>Allow user to <span style="text-transform: uppercase;">${mode}</span></td>
</tr>`;
if($(this).is(":checked")) {
$("#tableBody").append(rowTemp)
}else{
$("[data-mode='"+ mode +"']").remove();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table id="permissionsTable">
<thead>
<th>Name</th>
<th>Slug</th>
<th>Description</th>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<div id="alloptions">
<ul>
<li>
<input type="checkbox" name="option1" value="Play" />Play</li>
<li>
<input type="checkbox" name="option1" value="Create" />Create</li>
<li>
<input type="checkbox" name="option1" value="Delete" />Delete</li>
</ul>
</div>
You can just use the append function.
The logic will be quite easy.
$(".chx").change(function() {
var row = document.createElement("tr");
if(this.checked) {
var v = $(this).val();
row.innerHTML = `<td>${v} Game</td>
<td>${v.toLowerCase()}-Game</td>
<td>Allow user to ${v.toUpperCase()} a Game</td>`;
row.setAttribute("name",$(this).val());
$('#tableBody').append(row);
}
else{
$("tr[name="+$(this).val()+"]").remove();
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<body>
<table id="permissionsTable">
<thead>
<th>Name</th>
<th>Slug</th>
<th>Description</th>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<div id="alloptions">
<ul>
<li>
<input type="checkbox" value="Play" class="chx" />Play</li>
<li>
<input type="checkbox" value="Create" class="chx"/>Create</li>
<li>
<input type="checkbox" value="Delete" class="chx" />Delete</li>
</ul>
</div>
</body>
</html>

Append data to html table

I'm trying to add more data to the table below using JavaScript.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Home Page</title>
<script type="text/javascript" src="assets/style.js"></script>
</head>
<body>
<br><br><br><br><br>
<input type="text" id="personName" autofocus>
<button type="button" onclick="addData();">Append Information</button> <br><br><br><br><br>
<table>
<tr>
<th>Client Name</th>
</tr>
<tr>
<td>James Bond 007</td>
</tr>
<div id="addDataHere">
</div>
</table>
</body>
</html>
style.js Used is below:
function addData(){
var personName = document.getElementById("personName").value;
//console.log(personName);
var getOlderInformation = document.getElementById("addDataHere").innerHTML;
document.getElementById("addDataHere").innerHTML = getOlderInformation + "<tr><td>" + personName + "</tr></td>";
}
Expected Output Results:
Client Names James Bond 007 Tom Cruise ............ ............ ............ ............
This should get you started.
function addData() {
var personName = document.getElementById("personName").value;
var newRow = document.createElement("tr");
var newCell = document.createElement("td");
newCell.innerHTML = personName;
newRow.append(newCell);
document.getElementById("rows").appendChild(newRow);
document.getElementById("personName").value = '';
}
<input type="text" id="personName" autofocus>
<button type="button" onclick="addData();">Append Information</button> <br><br><br><br><br>
<table>
<tr>
<th>Client Name</th>
</tr>
<tbody id="rows">
<tr>
<td>James Bond 007</td>
</tr>
</tbody>
</table>
You were on the correct path, but an important note is that you were trying to use a div inside of a table. A table has very specific structure that has to be matched if you want it to render properly.
You are able to put div elements inside of a td or a th, but not inside of the table element itself. Check out this link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table
you can use a list to match what you need here's the code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Home Page</title>
</head>
<body>
<input type="text" id="personName" autofocus>
<button type="button" onclick="addData();">Append Information</button>
<p>Client Name</p>
<ul id="mylist">
<li>James Bond 007</li>
</ul>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
and the use adddata() function code like this
`function addData(){
var mylist=document.getElementById("mylist");
var personName=document.getElementById("personName").value;
var node = document.createElement("LI");
var textnode = document.createTextNode(personName);
node.appendChild(textnode);
mylist.appendChild(node);
}`
I hope this helps you :)
You can use an approach similar to what you are attempting: getting the innerHTML, appending some new html, and then replacing the innerHTML. But, you need to get the innerHTML of your table (not the element you nested inside of it).
For example (replaced your button onclick with an event listener).
const personName = document.getElementById('personName');
const appendButton = document.getElementById('appendButton');
const nameTable = document.getElementById('nameTable');
appendButton.addEventListener('click', (event) => {
let content = nameTable.innerHTML;
content += '<tr><td>' + personName.value + '</td></tr>';
nameTable.innerHTML = content;
});
<input type="text" id="personName" autofocus>
<button type="button" id="appendButton">Append Information</button>
<table id="nameTable">
<tr>
<th>Client Name</th>
</tr>
<tr>
<td>James Bond 007</td>
</tr>
</table>
Depending on the complexity of what you are doing, it may be faster to go the createElement / appendChild route suggested in the other answers if you also use use createDocumentFragment. Another example:
appendButton.addEventListener('click', (event) => {
const frag = document.createDocumentFragment();
const tr = document.createElement('tr');
const td = document.createElement('td');
td.appendChild(document.createTextNode(personName.value));
tr.appendChild(td);
frag.appendChild(tr);
nameTable.appendChild(frag);
});
<input type="text" id="personName" autofocus>
<button type="button" id="appendButton">Append Information</button>
<table id="nameTable">
<tr>
<th>Client Name</th>
</tr>
<tr>
<td>James Bond 007</td>
</tr>
</table>
You want to use appendchild. Check this out for some
Good examples https://www.w3schools.com/jsref/met_node_appendchild.asp . You want to loop through the data adding a row to a table , one row at a time

JQuery can't get input value from dynamically created field

Receiving value from static field when keyup based on input field class(.inputclass) method, but once add field dynamically its not get the value.
Below the sample code, Please help.
$(function(){
$(document).ready(function(){
$(".inputclass").keyup(function() {
alert($(this).val());
});
});
});
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
<tr>
<td>Field 1</td>
<td><input type="text" class="inputclass" /></td>
</tr>
<script>
var counter =1;
$(function(){
$('#addNew').click(function(){
counter += 1;
$('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
});
});
</script>
</table><br/>
<input type="button" id="addNew" value=" ± Add New Field"/>
</form>
This is because when you assigned the event handler, it only assigned to the existing elements at the time.
Delegate to the document:
$(document).on('keyup', '.inputclass', function(){
alert($(this).val())
});
When you delegate to a parent or the document, you are using the event that bubbles up and so it doesn't matter if there are dynamic elements.
$(function(){
$(document).ready(function(){
$(document).on('keyup', '.inputclass', function(){
alert($(this).val());
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
<tr>
<td>Field 1</td>
<td><input type="text" class="inputclass" /></td>
</tr>
<script>
var counter =1;
$(function(){
$('#addNew').click(function(){
counter += 1;
$('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
});
});
</script>
</table><br/>
<input type="button" id="addNew" value=" ± Add New Field"/>
</form>

Post dynamic content with ajax setInterval

I have a multiple tables as below, i want to print the name every 2 seconds on my first table without interrupting table2, if i use innerHTML it's always printing on top (above table1 & table2, but i need the variable on a specific location like in my case table1, if i use document.write on change() function it's keep looping the function infinitely and not coming out means table1 & table2 not showing up? could you please suggest the better way to resolve this?
I have the following code on my update.php
<html>
<head>
<link href="css/sample.css" rel="stylesheet" type="text/css" />
<div id="changeText" ></div>
<script type="text/javascript">
var text = ["Welcome", "David", "Paul", "John"];
var counter = 0;
var elem = document.getElementById("changeText");
function change() {
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0;
}
</script>
<body>
<tr>
<td>
<table align="left" width=15%>
<td <B><font color="green">Name:<script type="text/javascript">setInterval(change, 2000);
</script>
</font><br>
</td>
</table>
<table id="sample" width=70% cellpadding="2" cellspacing="1" border="1">
<th class="sno" colspan="2">SNO</th>
<th class="fname" colspan="2">FIRST NAME</th>
<th class="lname" colspan="2">LAST NAME</th>
</table>
</td>
</tr>
</body>
</html>
My goal is print the array of text under this tag
<td <B><font color="green">Name:<script type="text/javascript">setInterval(change, 2000);</script></font>
it should keep printing every 2 seconds with a name change...
You had some syntax errors :
http://jsfiddle.net/gFWeF/6/
<html>
<head>
<link href="css/sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
<tr>
<td>
<table align="left" width=15%>
<td><font color="green">Name:</font>
<span id="myname"></span>
</td>
</table>
<table id="sample" width=70% cellpadding="2" cellspacing="1" border="1">
<th class="sno" colspan="2">SNO</th>
<th class="fname" colspan="2">FIRST NAME</th>
<th class="lname" colspan="2">LAST NAME</th>
</table>
</td>
</tr>
</body>
</html>
<script>
var text = ["Welcome", "David", "Paul", "John"];
var counter = 0;
var elem = document.getElementById("myname");
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) counter = 0;
}
change();
setInterval(function() {
change()
}, 2000);
</script>

Categories

Resources