Javascript CRUD - javascript

My problem is that the edit function will display undefined in input field but in my console it displays the img url..
Can you please correct my script why it displays undefined
This is my js code, where I created 3 function,the , and
my.js
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row(){
var new_image=document.getElementById("new_image").value;
var new_title=document.getElementById("new_title").value;
var new_description=document.getElementById("new_description").value;
if (new_image&&new_title&&new_description != "") {
var table=document.getElementById("data_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML=
"<div id='row"+table_len+"'><img id='image_row"+table_len+"' src = "+new_image+"><div id='title_row"+table_len+"'>"+new_title+
"</div><div id='description_row"+table_len+"'>"+new_description+"</div><div><input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'><input type='button' value='Edit' class='edit' onclick='edit_row("+table_len+")'></div></div>";
document.getElementById("new_image").value="";
document.getElementById("new_title").value="";
document.getElementById("new_description").value="";
}
}
function edit_row(no){
var image=document.getElementById("image_row"+no).getAttribute("src");
console.log(image);
var title=document.getElementById("title_row"+no);
console.log(title);
var description=document.getElementById("description_row"+no);
console.log(description);
var image_data = image.innerHTML;
var title_data = title.innerHTML;
var description_data =description.innerHTML;
document.getElementById("new_image").value=image_data;
document.getElementById("new_title").value=title_data;
document.getElementById("new_description").value=description_data;
}
This part is my html code, why I only have div and tables
index.html
<div id="wrapper">
<h1 align="center">My Todo App</h1>
<div id="container">
<form id="myForm">
<table align='center' cellspacing=2 cellpadding=5>
<tr>
<th>Image Link</th>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td><input type="text" id="new_image"></td>
<td><input type="text" id="new_title"></td>
<td><input type="text" id="new_description"></td>
<td><input type="button" class="add" onclick="add_row();" value="SAVE"></td>
</tr>
</table>
</form>
</div>
<div id="content_container">
<div>
<table align='center' cellspacing=2 cellpadding=5 id="data_table">
</table>
</div>
</div>
</div>
and also how to append the new edited data when clicking the save button, in my case it will add another row.

Remove image.innerHTML inside function edit_row(no)
Added new function as per your question
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row(){
var new_image=document.getElementById("new_image").value;
var new_title=document.getElementById("new_title").value;
var new_description=document.getElementById("new_description").value;
if (new_image&&new_title&&new_description != "") {
var table=document.getElementById("data_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML=
"<div class='myrow'><div id='row"+table_len+"'><img id='image_row"+table_len+"' src = "+new_image+"><div id='title_row"+table_len+"' class='titleData'>"+new_title+
"</div><div class='descData' id='description_row"+table_len+"'>"+new_description+"</div><div><input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'><input type='button' value='Edit' class='edit' onclick='edit_row("+table_len+",this)'></div></div></div>";
document.getElementById("new_image").value="";
document.getElementById("new_title").value="";
document.getElementById("new_description").value="";
}
}
function edit_row(no,ref){
ref.value="Save";
ref.removeAttribute("onclick");
var image=document.getElementById("image_row"+no).getAttribute("src");
console.log(image);
var title=document.getElementById("title_row"+no);
console.log(title);
var description=document.getElementById("description_row"+no);
console.log(description);
var image_data = image; // remove image.innerHTML
var title_data = title.innerHTML;
var description_data =description.innerHTML;
document.getElementById("new_image").value=image_data;
document.getElementById("new_title").value=title_data;
document.getElementById("new_description").value=description_data;
ref.setAttribute("onclick","saveEdit(this,'"+no+"')");
}
function saveEdit(ref,no)
{
var new_image=document.getElementById("new_image").value;
var new_title=document.getElementById("new_title").value;
var new_description=document.getElementById("new_description").value;
var parent= (ref.parentElement).parentElement;
var img=parent.firstChild.setAttribute("src",new_image);
var list = document.getElementById(parent.id);
var title=list.getElementsByClassName("titleData")[0];
var desc=list.getElementsByClassName("descData")[0];
title.innerHTML=new_title;
desc.innerHTML=new_description;
ref.value="Edit";
ref.removeAttribute("onclick");
ref.setAttribute("onclick","edit_row("+no+",this)");
document.getElementById("new_image").value="";
document.getElementById("new_title").value="";
document.getElementById("new_description").value="";
}
<div id="wrapper">
<h1 align="center">My Todo App</h1>
<div id="container">
<form id="myForm">
<table align='center' cellspacing=2 cellpadding=5>
<tr>
<th>Image Link</th>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td><input type="text" id="new_image"></td>
<td><input type="text" id="new_title"></td>
<td><input type="text" id="new_description"></td>
<td><input type="button" class="add" onclick="add_row();" value="SAVE"></td>
</tr>
</table>
</form>
</div>
<div id="content_container">
<div>
<table align='center' cellspacing=2 cellpadding=5 id="data_table">
</table>
</div>
</div>
</div>

Related

My submited table does not show on the browser

I have a scoreboard where the user can enter the score and when the user presses the "Submit" button it will show a table that will contain the information that the user has entered. But when I try it in the browser, my table doesn't show the information that was entered in the previous form, it only show the table heading. Let me explain like below:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.getElementById("tableScore");
var row = table.insertRow(i);
var number = row.insertCell(0);
var name = row.insertCell(1);
var math = row.insertCell(2);
var physics = row.insertCell(3);
var chemistry = row.insertCell(4);
var avg = row.insertCell(5);
number.innerHtml = i;
name.innerHtml = testScore.name;
math.innerHtml = testScore.math;
physics.innerHtml = testScore.physics;
chemistry.innerHtml = testScore.chemistry;
avg.innerHtml = testScore.avg;
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
In js code you have used innerHtml instead of innerHTML.
Updated code:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.getElementById("tableScore");
var row = table.insertRow(i);
var number = row.insertCell(0);
var name = row.insertCell(1);
var math = row.insertCell(2);
var physics = row.insertCell(3);
var chemistry = row.insertCell(4);
var avg = row.insertCell(5);
number.innerHTML = i;
name.innerHTML = testScore.name;
math.innerHTML = testScore.math;
physics.innerHTML = testScore.physics;
chemistry.innerHTML = testScore.chemistry;
avg.innerHTML = testScore.avg;
i++;
}
#import url('https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap');
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
</body>
</html>
When you use insertCell you need to use innerHTML or appendChild instead of the non-existent innerHtml
Also you do not need to have any integer in insertCell/Row
Also your HTML was invalid
number.appendChild(document.createTextNode(i));
name.appendChild(document.createTextNode(testScore.name));
math.appendChild(document.createTextNode(testScore.math));
physics.appendChild(document.createTextNode(testScore.physics));
chemistry.appendChild(document.createTextNode(testScore.chemistry));
avg.appendChild(document.createTextNode(testScore.avg));
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physics = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.querySelector("#tableScore tbody");
var row = table.insertRow();
var number = row.insertCell();
var name = row.insertCell();
var math = row.insertCell();
var physics = row.insertCell();
var chemistry = row.insertCell();
var avg = row.insertCell();
number.appendChild(document.createTextNode(i));
name.appendChild(document.createTextNode(testScore.name));
math.appendChild(document.createTextNode(testScore.math));
physics.appendChild(document.createTextNode(testScore.physics));
chemistry.appendChild(document.createTextNode(testScore.chemistry));
avg.innerHTML = testScore.avg; // alternative to appendChild
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table border="2" id="tableScore">
<thead>
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</thead>
<tbody>
</tbody>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
You have some misspelled variables but you can also minimize your output with only one global innerHTML like in my example below:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
//MINIMIZED VERSION
document.getElementById("tableScore").innerHTML +=
"<td>" + i + "</td>" +
"<td>" + testScore.name + "</td>" +
"<td>" + testScore.math + "</td>" +
"<td>" + testScore.physical + "</td>" +
"<td>" + testScore.chemistry + "</td>" +
"<td>" + testScore.avg + "</td>";
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td>
<input name="math" id="math" type="number" />
</td>
</tr>
<tr>
<td>Physics:</td>
<td>
<input name="physics" id="physics" type="number" />
</td>
</tr>
<tr>
<td>Chemistry:</td>
<td>
<input name="chemical" id="chemical" type="number" />
</td>
</tr>
<td>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>

I want to add new data from second table to main table

I want to add new data to the main table using the checkbox option, but the data added is not the same as the selected data. this is my code ...
<table border="1" id="table2">
<tr>
<td>Raka</td>
<input type="hidden" id="fname" value="Raka">
<td>Gilbert</td>
<input type="hidden" id="lname" value="Gilbert">
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<input type="hidden" id="fname" value="Achyar">
<td>Lucas</td>
<input type="hidden" id="lname" value="Lucas">
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<script>
$(document).on('click', '#Add', function() {
$("table").find('input[name="chk"]').each(function(){
if($(this).is(":checked")){
var fname = $('#fname').val();
var lname = $('#lname').val();
var newData = '<tr>'+
'<td>'+fname+'</td>'+
'<td>'+lname+'</td>'+
'<tr>';
$('table').append(newData);
}
});
})
</script>
You need to change your id="fname" to class="fname" and get the input value closest to checkbox. Currently you are getting data from the first inputs as they have the same id's.
function valueExists(value) {
if (!value) {
return true;
}
let exists = false;
$("#main-table").find('tr').each(function() {
let fname = $(this).find("td:nth-child(1)").text(),
lname = $(this).find("td:nth-child(2)").text();
const fullName = `${fname}${lname}`;
if (value.toLowerCase() === fullName.toLowerCase()) {
exists = true;
}
});
return exists;
}
$(document).on('click', '#add', function() {
$("table").find('input[name="chk"]').each(function(e) {
if ($(this).is(":checked")) {
var fname = $(this).parents('tr').find('.fname').val();
var lname = $(this).parents('tr').find('.lname').val();
if (valueExists(`${fname}${lname}`)) return;
var newData = '<tr>' +
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<tr>';
$('#main-table').append(newData);
}
});
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Main Table</h1>
<table class="table table-dark" border="1" id="main-table">
</table>
<hr>
<h1>Second table</h1>
<table border="1" id="table2">
<tr>
<td class="name">Raka</td>
<input type="hidden" class="fname" value="Raka">
<td class="last">Gilbert</td>
<input type="hidden" class="lname" value="Gilbert">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
<tr>
<td class="name">Achyar</td>
<input type="hidden" class="fname" value="Achyar">
<td class="last">Lucas</td>
<input type="hidden" class="lname" value="Lucas">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="add" name="button">Add</button>
Try this. I have used plain javascript
document.addEventListener("click", function() {
[...document.querySelectorAll("input[name='chk']")].forEach(data => {
console.log(data);
if (data.checked) {
const fname = document.getElementById("fname").value;
const lname = document.getElementById("lname").value;
const newData = `<tr><td>${ fname }</td><td>${ lname }</td</tr>`;
// "<tr>" + "<td>" + fname + "</td>" + "<td>" + lname + "</td>" + "<tr>";
document.getElementById("table2").innerHTML += newData;
}
});
});
Hope was useful. If any flaws please update
Here is a neater solution, using 2 tables as requested, without hidden inputs and a better use of 'tables' and 'trs' in jquery
$(function(){
$("#btnAdd").click(function(){
let table1 = $("#table1");
table2 = $("#table2");
$.each(table2.find('tr'), function(i, tr){
tr = $(tr);
let new_tr = $('<tr>');
if (tr.find("td input").is(":checked")) {
let fname = tr.find("td:nth-child(1)").html(),
lname = tr.find("td:nth-child(2)").html();
new_tr.append(
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<td><input type="checkbox" name="chk"></td>'
);
table1.append(new_tr)
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
TABLE 1
<table border="1" id="table1">
</table>
<hr/>
TABLE 2
<table border="1" id="table2">
<tr>
<td>Raka</td>
<td>Gilbert</td>
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<td>Lucas</td>
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="btnAdd">Add</button>

multiple pages should read data from central webpage

I am trying to develop a information based website to showcase list of automation projects are completed by my team. Idea is to create 3 webpages
Page1, will have information about the automation projects delivered to the clients (For clients to see)
Page2, will have the metrics like time took before automation and time after automation etc. This will be presented in the bar and circular graphs (For management to see)
Page3, This should act like central page and data entered here should reflect in other pages. This will be in table format
Problem here is I am struggling to write code such that page1 and page 2 will automatically read corresponding data from page3. Any help with code, links or suggestions is highly appreciated
enter code here
here is our code:
html 1: dynamically added rows with edit and save delete buttons to a table
<body>
<div class="marginT5 float_left"><img src="black.png" align="right"
width="260" height="100"
/></div>
<div class="main_navline">
<div > </div>
<div id ="test" title="" class="manu" align="center" > </div>
<div > </div>
<form onsubmit="passing()" id="myForm" method="get" >
<table class="data_table" id="data_table" >
<tr>
<th>Level of the task</th>
<th>Task</th>
<th>Automation ID</th>
<th>Activity</th>
</tr>
<tr>
<td><input type="text" id="new_name"></td>
<td><input type="text" id="new_type"></td>
<td><input type="text" id="new_url"></td>
<td><input type="text" id="new_description"></td>
<td><input type="button" class="add" onclick="add_row();" value="Add Row">
</td>
</tr>
</table>
</form>
html 2: the url and description of each row entered in htm1 need to be displayed in html2
<body >
<div class="marginT5 float_left"><img src="black.png" align="right" width="260" height="100"
/></div>
<div class="main_navline"> </div>
<div > </div>
<div class="inner_wrapper">
<div class="manu" align="center" >TEAM</div>
<div class="w3-container">
<form name="form1" method="get">
<table>
<tr>
<td id="here"></td>
</tr>
</table>
</form>
ourjavascript:
function edit_row(no)
{
document.getElementById("save_button"+no).disabled = false;
document.getElementById("edit_button"+no).disabled = true;
/* document.getElementById("edit_button"+no).style.display="none";
document.getElementById("save_button"+no).style.display="block"; */
var name=document.getElementById("name_row"+no);
var url=document.getElementById("url_row"+no);
var type=document.getElementById("type_row"+no);
var description=document.getElementById("description_row"+no);
var name_data=name.innerHTML;
var url_data=url.innerHTML;
var type_data=type.innerHTML;
var description_data=description.innerHTML;
name.innerHTML="<input type='text' id='name_text"+no+"' value='"+name_data+"'>";
url.innerHTML="<input type='text' id='url_text"+no+"' value='"+url_data+"'>";
type.innerHTML="<input type='text' id='type_text"+no+"' value='"+type_data+"'>";
description.innerHTML="<input type='text' id='description_text"+no+"' value='"+description_data+"'>";
}
function save_row(no)
{
var name_val=document.getElementById("name_text"+no).value;
var url_val=document.getElementById("url_text"+no).value;
var type_val=document.getElementById("type_text"+no).value;
var description_val=document.getElementById("description_text"+no).value;
document.getElementById("name_row"+no).innerHTML=name_val;
document.getElementById("url_row"+no).innerHTML=url_val;
document.getElementById("type_row"+no).innerHTML=type_val;
document.getElementById("description_row"+no).innerHTML=description_val;
document.getElementById("save_button"+no).disabled = true;
document.getElementById("edit_button"+no).disabled = false;
/* 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_name=document.getElementById("new_name").value;
var new_url=document.getElementById("new_url").value;
var new_type=document.getElementById("new_type").value;
var new_description=document.getElementById("new_description").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='name_row"+table_len+"'>"+new_name+"</td><td id='url_row"+table_len+"'>"+new_url+"</td><td id='type_row"+table_len+"'>"+new_type+"</td><td id='description_row"+table_len+"'>"+new_description+"</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' disabled onclick='save_row("+table_len+")'> <input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_url").value="";
document.getElementById("new_type").value="";
document.getElementById("new_description").value="";
}

how to get html table data to an Array?

I am using PHP Codeigniter.I don't have good knowledge in JavaScript. My problem is that I have a table with editable columns and when I click on the submit button I want to send the table data to the Codeigniter function using POST method.
HTML code
<div class="col-md-12 top-20 padding-0">
<div class="col-md-12">
<div class="panel">
<div class="panel-heading"><h3>Data Tables</h3></div>
<div class="panel-body">
<div class="responsive-table">
<table id="data_table" class="table table-striped table-bordered" width="100%" cellspacing="0">
<tr>
<th>Name</th>
<th>Country</th>
<th>Age</th>
<th>Action</th>
</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" onclick="add_row();" value="Add Row"></td>
</tr>
</table>
<input type="button" name="check" onclick="clik();">
</div>
</div>
</div>
</div>
</div>
JavaScript for editable table
function edit_row(no)
{
document.getElementById("edit_button"+no).style.display="none";
document.getElementById("save_button"+no).style.display="block";
var name=document.getElementById("name_row"+no);
var country=document.getElementById("country_row"+no);
var age=document.getElementById("age_row"+no);
var name_data=name.innerHTML;
var country_data=country.innerHTML;
var age_data=age.innerHTML;
name.innerHTML="<input type='text' id='name_text"+no+"' value='"+name_data+"'>";
country.innerHTML="<input type='text' id='country_text"+no+"' value='"+country_data+"'>";
age.innerHTML="<input type='text' id='age_text"+no+"' value='"+age_data+"'>";
}
function save_row(no)
{
var name_val=document.getElementById("name_text"+no).value;
var country_val=document.getElementById("country_text"+no).value;
var age_val=document.getElementById("age_text"+no).value;
document.getElementById("name_row"+no).innerHTML=name_val;
document.getElementById("country_row"+no).innerHTML=country_val;
document.getElementById("age_row"+no).innerHTML=age_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_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;
var row = 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' 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_name").value="";
document.getElementById("new_country").value="";
document.getElementById("new_age").value="";
}
So in the given editable table data I want to push to my codeigniter function.
the best way now is to use Ajax in order to post those javascript value to the Codeigniter function
example on a simple ajax call :
var newName = 'John Smith';
$.ajax('myservice/codigniter_Function?' + $.param({id: 'some-unique-id'}), {
method: 'POST',
data: {
name: newName
}
})
.then(
function success(name) {
if (name !== newName) {
alert('Something went wrong. Name is now ' + name);
}
},
function fail(data, status) {
alert('Request failed. Returned status of ' + status);
}
);
please check the source for more information on how to use ajax with javascript in details.
Since your question includes vanilla Javascript, my answer will use XMLHttpRequest(). I have created the following function to send post data to the back end.
function ajax_req(url, params) {
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
In your save_row() function, create parameters to send to the back end, like name=billy&age=21&country=us
function save_row(no) {
var name_val = document.getElementById("name_text" + no).value;
var country_val = document.getElementById("country_text" + no).value;
var age_val = document.getElementById("age_text" + no).value;
document.getElementById("name_row" + no).innerHTML = name_val;
document.getElementById("country_row" + no).innerHTML = country_val;
document.getElementById("age_row" + no).innerHTML = age_val;
document.getElementById("edit_button" + no).style.display = "block";
document.getElementById("save_button" + no).style.display = "none";
// send values to back end
var params = "name=" + name_val + "&country=" + country_val + "&age=" + age_val;
ajax_req('/savedata', params);
}
<form action="<php echo base_url('controller_name/ method_name')?>
method="POST">
<div class="col-md-12 top-20 padding-0">
<div class="col-md-12">
<div class="panel">
<div class="panel-heading"><h3>Data Tables</h3></div>
<div class="panel-body">
<div class="responsive-table">
<table id="data_table" class="table table-striped table-bordered" width="100%" cellspacing="0">
<tr>
<th>Name</th>
<th>Country</th>
<th>Age</th>
<th>Action</th>
</tr>
<tr>
<td><input type="text" id="new_name" name="newname"></td>
<td><input type="text" id="new_country" name="country"></td>
<td><input type="text" id="new_age" name="age"></td>
</tr>
</table>
<input type="submit" name="check" class="btn btn-primary">
</div>
</div>
</div>
</div>
In Your Controller
public function function_name()
{
$post = $this>input->post();
$data = array(
'name' =>$post['newname'],
'country' =>$post['country'],
'age' =>$post['age'],
);
$this->load->model('model_name');
$this->model_name->function_name($data);
}
In your model
public function function_name($data)
{
return $this->db->insert('table_name', $data);
}

$(.class).click(function(){}) not working [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I am facing problem in $(.class).click(function(){}); which is not working with my code.
Can any one help me on this.
My code is:
whenever i click on edit button popup div open but since click event not fire so text boxes in popup not filled due to which i am not able to update the record.
Please help me to resolve the issue:
$(document).ready(function(){
$(".btn-ed").click(function(e) {
try{
var $row = $(this).closest("tr");
var id = $row.find('td:eq(0)').text();
var className = $row.find('td:eq(1)').text();
var schoolName = $row.find('td:eq(2)').text();
var status = $row.find('td:eq(3)').text();
$("#txtId").val(id);
$("#txtClass").val(className);
$("#txtSchool").val(schoolName);
$("#ddlStatus").val((status=='Active'?'1':'0'));
}
catch(err){alert(err);}
});
$("#btnUpdate").click(function() {
var id = $('#txtId').val();
var status = $("#ddlStatus").val();
$.ajax({
cache: false,
type:"post",
url:"updateClass.php",
data: {cId: id, cStatus: status},
success:function(ret){
if(ret=='1')
{
location.reload(true);
window.location="?u=1&#close";
}
else
{
location.reload(true);
window.location="?u=0&#close";
}
}
});
});
});
$(document).ready(function(){
try{
getClassData();
var res = GetParameterValues('u');
var res1='';
if(res)
{
res1 = res.split('#')[0];
if(res1=='1')
{
$("#msg-inf").hide();
$("#msg-fail").hide();
$("#msg-sucess").show();
}
else
{
$("#msg-inf").hide();
$("#msg-fail").show();
$("#msg-sucess").hide();
}
}
}
catch(er){alert(er);}
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
function getClassData(){
$.ajax({
cache: false,
type:"post",
url:"classdata.php",
datatype: 'json',
data: {qry: 'ClassData'},
success:function(ret){
var jobj = $.parseJSON(ret);
loadTable(jobj);
}
});
}
function loadTable(dt){
try{
var dLength = dt.length;
var tableData = '';
if(dLength > 0){
for(var i=0;i < dLength; i++){
tableData += "<tr class='data'><td class='data' width='30px'>"+dt[i].id+"</td><td class='data' width='70px'>"+dt[i].class_name+"</td><td class='data' width='70px'>"+dt[i].school_name+"</td><td class='data' width='60px'>"+(dt[i].is_active=='1'?'Active':'Deacive')+"</td><td class='data' width='70px'><a href='#openModal'><button id='button' class='btn-ed'>Edit</button></a></td></tr>";
}
$("#tblClass").append(tableData).show();
}
}
catch(err){alert(err);}
}
});
and HTML
<body>
<?php
include 'header.php';
?>
<div id="wrapper">
<?php include 'left-sidebar.php'; ?>
<div id="rightContent">
<h3>Classes</h3>
<div><div class='informational' id="msg-inf">To update status of any class click on Edit button.</div>
<div class='failure' id="msg-fail" style="display:none;">Class status changing failed due to some error.</div>
<div class='success' id="msg-sucess" style="display:none;">Class status successfully changed. Reload page to view changes</div>
</div>
<table class="data" id="tblClass" style="display:none;">
<tr class="data">
<th class="data" width="30px">No</th>
<th class="data" width="70px">Class Name</th>
<th class="data" width='70px'>School Name</th>
<th class="data" width='60px'>Status</th>
<th class="data" width="70px">Action</th>
</tr>
<!--<tr class="data">
<td class="data" width="30px"><?php echo $row['id'];?></td>
<td class="data" width="70px"><?php echo $row['class_name'];?></td>
<td class="data" width="70px"><?php echo $row['school_name'];?></td>
<td class="data" width="60px"><?php echo $status;?></td>
<td class="data" width="70px">
<button id="button" class="btn-ed">Edit</button>
</td>
</tr>-->
</table>
</div>
<div class="clear"></div>
<!-- modal dialog div --->
<div id="openModal" class="modalDialog">
<div> X
<h2>Update Class Status</h2>
<div style="text-align:center;">
<table width="100%">
<tr>
<td>Id</td>
<td><input type="text" id="txtId" disabled="true"></td>
</tr>
<tr>
<td>Class:</td>
<td><input type="text" id="txtClass" disabled="true"></td>
</tr>
<tr>
<td>School</td>
<td><input type="text" id="txtSchool" disabled="true"></td>
</tr>
<tr>
<td>Status</td>
<td><select id="ddlStatus"><option value="1">Active</option><option value="0">Deactive</option></select></td>
</tr>
<tr><td></td>
<td>
<button id="btnUpdate" class="button">Update</button>
Cancel
</td>
</tr>
</table>
</div>
</div>
</div>
Thanks in advance..
When dynamically adding an element to the DOM, you cannot attach an event handler to it on document.ready. You need to redefine you event handler to the document, and "look" for the element instead.
The handler should be:
$(document).on('click', '.btn-ed', function(e) {
try{
var $row = $(this).closest("tr");
var id = $row.find('td:eq(0)').text();
var className = $row.find('td:eq(1)').text();
var schoolName = $row.find('td:eq(2)').text();
var status = $row.find('td:eq(3)').text();
$("#txtId").val(id);
$("#txtClass").val(className);
$("#txtSchool").val(schoolName);
$("#ddlStatus").val((status=='Active'?'1':'0'));
}
catch(err){alert(err);}
});
You can try this:
$(document.body).on('click', '.btn-ed' ,function(e){
// your code
});

Categories

Resources