make each table value display in each textbox - javascript

I have this html table and 2 textboxes:
<table id="myTbl">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
<input type="text" name="txt" id="txt" >
<input type="text" name="txt" id="txt2" >
I want when reload the page, the values 1 and 2 must display in each textbox. How can I do it?
I have tried this js code but wrong and I want it auto display, not to click it:
var cells = document.querySelectorAll('#myTbl tbody ');
Array.from(cells).forEach(function (elem) {
elem.addEventListener('click', function () {
document.getElementById('txt').value = this.textContent;
})
})

var tbody = document.getElementsByTagName('tbody')[0]
var input1 = document.getElementById('txt')
var input2 = document.getElementById('txt2')
input1.value = tbody.getElementsByTagName('td')[0].textContent
input2.value = tbody.getElementsByTagName('td')[1].textContent

Related

Why is .append() creating 2 rows in this code when I click Add New button?

Why is .append() creating 2 identical rows in this code when I click Add New button? I don't see why 2 appends happen. Am I misunderstanding something? This doesn't happen with vanilla javascript but happens with jquery.
I added the table which includes the tbody tag at the end of the table where I would like to append the template string in function onAddProduct(e).
(Note: I removed html since it was an assignment.)
here is the code snippet
$(function() {
var $formEl = $('form');
var $tbodyEl = $('tbody');
var $tableEl = $('table');
function onAddProduct(e) {
e.preventDefault();
var $pName = $('#pname').val();
var $pCat = $('#pcat').val();
var $pPrice = $('#pprice').val();
$tbodyEl.append(`
<tr>
<td>${$pName}</td>
<td>${$pCat}</td>
<td>${$pPrice}</td>
<td><button class="deleteBtn">Delete</button></td>
</tr>
`);
}
function onDeleteRow(e) {
if (!e.target.classList.contains("deleteBtn")) {
return;
}
const btn = e.target;
btn.closest("tr").remove();
}
//formEl.addEventListener("submit", onAddProduct);
$formEl.on({
submit: onAddProduct
});
//tableEl.addEventListener("click", onDeleteRow);
$tableEl.on({
click: onDeleteRow
});
});
Consider the following.
$(function() {
var $formEl = $('form');
var $tbodyEl = $('tbody');
var $tableEl = $('table');
function onAddProduct(e) {
e.preventDefault();
var row = $("<tr>").appendTo($("tbody", $tableEl));
$("<td>").html($('#pname').val()).appendTo(row);
$("<td>").html($('#pcat').val()).appendTo(row);
$("<td>").html($('#pprice').val()).appendTo(row);
$("<td>").html("<button class='deleteBtn'>Delete</button>").appendTo(row);
return;
}
function onDeleteRow(e) {
if (!e.target.classList.contains("deleteBtn")) {
return;
}
if (confirm("Are you sure you want to delete this Product?")) {
$(e.target).closest("tr").remove();
}
}
$formEl.on({
submit: onAddProduct
});
$tableEl.on({
click: onDeleteRow
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Add Product</h4><br>
<form>
<label for="pname">Product Name:</label>
<input type="text" id="pname" name="pname">
<label for="pcat">Product Category:</label>
<input type="text" id="pcat" name="pcat">
<label for="pprice">Product price:</label>
<input type="text" id="pprice" name="pprice">
<button type="submit" class="addBtn">Add New</button>
</form>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Product Category</th>
<th>Product Price</th>
<td> </td>
</tr>
</thead>
<tbody>
</tbody>
</table>
I am not able to replicate the issue with this code. Only 1 Row is added.
Your table is missing the <tbody> around the rows you have added, so the browser is adding it in to create a valid table. This results in 2 <tbody> elements, and is why rows are being added twice:
It can be prevented by putting the header and body rows inside the <thead> and <tbody> elements that the browser wants, seen below in the snippet -
$(function() {
var $formEl = $('form');
var $tbodyEl = $('tbody');
function onAddProduct(e) {
e.preventDefault();
var $pName = $('#pname').val();
var $pCat = $('#pcat').val();
var $pPrice = $('#pprice').val();
$tbodyEl.append(`
<tr>
<td>${$pName}</td>
<td>${$pCat}</td>
<td>${$pPrice}</td>
</tr>
`);
}
$formEl.on({
submit: onAddProduct
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="productTable" border="1">
<thead>
<tr>
<th>Product Name</th>
<th>Product Category</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>M&M</td>
<td>Snacks</td>
<td>$1.99</td>
</tr>
<tr>
<td>Table</td>
<td>Furniture</td>
<td>$1.99</td>
</tr>
<tr>
<td>Kale</td>
<td>Vegetables</td>
<td>$2.49</td>
</tr>
</tbody>
</table>
<h4>Add Product</h4><br>
<form>
<label for="pname">Product Name:</label>
<input type="text" id="pname" name="pname">
<label for="pcat">Product Category:</label>
<input type="text" id="pcat" name="pcat">
<label for="pprice">Product price:</label>
<input type="text" id="pprice" name="pprice">
<button type="submit" class="addBtn">Add New</button>
</form>

Create Javascript object from HMTL table

I have a table like
<table id="misc_inputs">
<thead>
<tr><th>Property</th><th>Input</th></tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td><input type="number" value="1"></td>
</tr>
<tr>
<td>b</td>
<td><input type="number" value="2"></td>
</tr>
...
I would like to convert that table to a Javascript object like
misc_inputs = {"a": 1, "b": 2, ...
How can the result be generated?
You can use below re-usable javascript method to convert any HTML table into Javascript object.
<table id="MyTable">
<thead>
<tr><th>Property</th><th>Input</th></tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td><input type="number" value="1"></td>
</tr>
<tr>
<td>b</td>
<td><input type="number" value="2"></td>
</tr>
</tbody>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function ConvertHTMLToJSObject(htmlTableId)
{
var objArr = {};
var trList = $('#' + htmlTableId).find('tr');
$('#' + htmlTableId).find('tbody tr').each(function ()
{
var row = $(this);
var key = $(row).first().text().trim();
var value = $(row).find('input').attr("value");
objArr[key] = value;
});
return objArr;
}
var obj = ConvertHTMLToJSObject("MyTable");
console.log(obj);
});
You can loop through each inputs and create the object:
var misc_inputs = {};
$("#misc_inputs input[type=number]").each(function(i, el){
var k = $(this).closest('td').prev().text();
return misc_inputs[k] = +el.value;
});
console.log(misc_inputs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="misc_inputs">
<thead>
<tr><th>Property</th><th>Input</th></tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td><input type="number" value="1"></td>
</tr>
<tr>
<td>b</td>
<td><input type="number" value="2"></td>
</tr>
</tbody>
</table>
Probably you can do it without any library but with jQuery it's easier. Something like that should work (not tested):
// Here we will store the results
var result = {};
// Ask jQuery to find each row (TR tag) and call a function for each
$('tr').each(function(){
// Inside a jQuery each() "this" is the current element, the TR tag in this example
var row = $(this);
// We ask jQuery to find every TD inside the current row (the second parameter of a jQuery selector is the parent node for your search). We take the first one and then we take the content of the tag
var label = $("td", row).first().text();
// We ask for an "input" tag inside the current row and we read its "value" attribute
var value = $("input", row).attr("value");
// Store everything in result
result[label] = value;
});

Editing form by double clicking element

I have a form, and I want to be able to edit any part of that form by double clicking it. So going from this:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>John Smith</td>
<td>johnsmith#gmail.com</td>
<td>+12345678</td>
</tr>
</table>
How can I by double-clicking an element, transform it to an input element?
For example: if I double click on John Smith, the HTML changes into this:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<form action="index.php" method="post">
<td><input type="text" value="John Smith" name="name" /></td>
<td>johnsmith#gmail.com</td>
<td>+12345678</td>
</form>
</tr>
</table>
So now I can change John's name.
Does someone know how to do it?
Try this, fields from the second row are editable with dblclick
document.querySelectorAll("table tr:nth-child(2) td").forEach(function(node){
node.ondblclick=function(){
var val=this.innerHTML;
var input=document.createElement("input");
input.value=val;
input.onblur=function(){
var val=this.value;
this.parentNode.innerHTML=val;
}
this.innerHTML="";
this.appendChild(input);
input.focus();
}
});
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>John Smith</td>
<td>johnsmith#gmail.com</td>
<td>+12345678</td>
</tr>
</table>
How about that:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td id="name">John Smith</td>
<td>johnsmith#gmail.com</td>
<td>+12345678</td>
</tr>
</table>
<script>
$("#name").dblclick(function(e) {
if (e.target.parentElement.nodeName != 'form') {
var form = $('<form action="index.php" method="post">');
var parent = $(e.target.parentElement);
parent.children().each(function(i, elem){
form.append(elem);
})
parent.empty();
parent.append(form);
}
})
</script>
It handles double click event and wraps all <td> elements inside <tr> into <form> tag.
I believe this will do what you want:
$("document").ready(function () {
var haveForm = false;
$("td").dblclick(function () {
var thisVal = $(this).html();
if (!haveForm) {
$("td").wrapAll('<form action="index.php" method="post" />');
haveForm = true;
}
$(this).html('<input type="text" value="' + thisVal + '" name="name" />');
});
});
jsFiddle
This makes use of jQuery's wrapAll() and safe guards against multiple form elements being created.

Get clicked column index from row click

I have a row click event. Recently had to add a checkbox to each row. How can I identify the clicked cell on row click event?
Or prevent row click when clicked on the checkbox.
Attempts: this.parentNode.cellIndex is undefined on the row click event.
function pop(row){
alert(row.cells[1].innerText);
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Do you want something like this? You can just check the type attribute of the source element of the event and validate whether to allow it or not, you can stop the event using e.stopPropagation();return;.
function pop(e, row) {
console.log(e.srcElement.type);
if(e.srcElement.type === 'checkbox'){
e.stopPropagation();
return;
}else{
console.log(row);
alert(row.cells[1].innerText);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event, this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
You should pass in the event details to your function and check the target property:
function pop(e){
// If the target is not a checkbox...
if(!e.target.matches("input[type='checkbox']")) {
alert(e.target.cellIndex);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event)">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Note: If you have nested elements inside the <td>, you might want to check e.target.closest("td") instead.
Note 2: You might need a polyfill for the matches method depending on which browsers you're supporting.
Here is an example if you don't want to attach a listener on every row :
document.getElementById("majorCities").addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var tr = e.target.parentElement.parentElement;
var city = tr.cells[1].innerHTML;
console.log(city+":checked="+checked);
}
});
<table id="majorCities" style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>London</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>Paris</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>New-York</td>
</tr>
</table>
window.pop = function(row){
console.log('here');
var parent = row.parentNode;
Array.from(row.parentNode.querySelectorAll('tr')).forEach(function(tr, index){
if (tr === row) {
alert(index)
}
})
}
https://jsfiddle.net/sz42oyvm/
Here is for the pleasure, another example with an object containing the cities' names and a method to draw the table with ids corresponding to the name of the clicked city, so getting the clicked name is easier.
(function () {
var mySpace = window || {};
mySpace.cities = {};
mySpace.cities.pointer = document.getElementById("majorCities");
mySpace.cities.names = ["Select","City"];
mySpace.cities.data = [{"name":"Paris"},{"name":"New Delhi"},{"name":"Washington"},{"name":"Bangkok"},{"name":"Sydney"}];
mySpace.cities.draw = function(){
this.pointer.innerHTML="";
var html = "";
html+="<tr>"
for(var i=0;i < this.names.length;i++){
html+="<th>"+this.names[i];
html+="</th>"
}
html+="</tr>"
for(var i=0;i < this.data.length;i++){
html+="<tr>"
html+="<td><input id='"+this.data[i].name+"' type='checkbox'/></td>"
html+="<td>"+this.data[i].name+"</td>"
html+="</tr>"
}
this.pointer.innerHTML=html;
}
mySpace.cities.draw();
mySpace.cities.pointer.addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var city = e.target.id;
console.log(city+":checked="+checked);
}
});
})();
table {width:25%;background:#ccc;border:1px solid black;text-align:left;}
td,tr {background:white;}
th:first-of-type{width:20%;}
<table id="majorCities">
</table>

Adding a row that is writable in HTML

I have made a table that can add a row. But I want the row to be writable. When the user clicks the addRow a new row will appear and the user can input a text on it. Can someone help me to do it? Thankyou so much.
the code is in the jsFiddle.
jsFiddle
Here is the solution in jsFiddle
http://jsfiddle.net/96oqxz9z/
All you need to add is a simple line:
$('#tbl1').append("<TR><TD></TD><TD><input type=\"text\"></TD></TR>");
Try this
Check here
function addRow() {
$('#addmore').append('<tr><td><input type="text" value="1"></td><td><input type="text" value="2"></td></tr><tr><td> </td></tr>')
};
$(document).on('click', '#add', function() {
var row = '<tr><td><input type="text" /></td></tr>';
$(this).closest('table').append(row);
})
td {
border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="add">add row </td>
</tr>
</table>
try using this:
function addRow() {
"use strict";
var table = document.getElementById("tbl1");
var row=table.insertRow(table.rows.length);
console.log(row);
var td1=row.insertCell(0);
var td11 = document.createElement("span");
td1.appendChild(td11);
var td2=row.insertCell(1);;
var td22 = document.createElement("input");
td22.type = "text";
td2.appendChild(td22);
td11.innerHTML = document.getElementById("a").innerHTML;
td2.value = document.getElementById("b").innerHTML;
row.appendChild(td1);
row.appendChild(td2);
table.children[0].appendChild(row);
}
<input type="button" onclick="addRow()" value="Add Row"/>
<TABLE id="tbl1">
<TR>
<TH></TH>
<TH id="a">Principal Name</TH>
<TH id="b">Principal Titles</TH>
</TR>
<TR>
<TD></TD>
<TD>Director Of Manager</TD>
</TR>
<TR>
<TD></TD>
<TD>President</TD>
</TR>
<TR>
<TD></TD>
<TD>Treasurer</TD>
</TR>
</TABLE>

Categories

Resources