How to display radio and checkbox values in table using javascript? - javascript

When I click display button it displays name and age but gender and checkbox is incorrect it displays first value only. I want to display which i select.
radio data and checkbox data should display.
(function setup() {
"use strict";
var NameElem = document.getElementById("name");
var genderElem = document.getElementById("gender");
var ageElem = document.getElementById("age");
var languageElem = document.getElementById("language");
var tableElem = document.getElementById("table");
document.getElementById("display").addEventListener("click", function() {
var newRow = tableElem.insertRow(-1);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(NameElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(1);
newText = document.createTextNode(genderElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(2);
newText = document.createTextNode(ageElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(3);
newText = document.createTextNode(languageElem.value);
[newCell.appendChild][1](newText);
NameElem.value = "";
genderElem.value = "";
ageElem.value = "";
languageElem.value = "";
tableElem.value = "";
});
})();
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="container">
<br>
<br>
<h3 class="text-center">Display answers of form fill in inside a table</h3>
<br>
<br>
<form>
<div class="form-group">
<label>First Name</label>
<input id="name" class="form-control form-control-sm" />
</div>
<div class="form-group">
<label>Age</label>
<input id="age" class="form-control form-control-sm" />
</div>
<div class="form-group">
Gender:<input type="radio" name="male" id="gender" value="male">Male
<input type="radio" name="female" id="gender" value="female">
<label for="female">Female</label>
</div>
<div class="form-group">
<label>Language</label>
<input type="checkbox" id="language" name="malayalam" value="Malayalam">Malayalam
<input type="checkbox" id="language" name="english" value="English">English
<input type="checkbox" id="language" name="hindi" value="Hindi">Hindi
</div>
<button type="button" id="display" class="btn btn-sm btn-primary">Display</button>
</form>
<br>
<br>
<table class="table border" id="table">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Language</th>
</tr>
</table>
<script type="text/javascript" src="form.js"></script>
</div>

Well, the code does exactly what you asked for.
var genderElem = document.getElementById("gender");
// returns the element with ID "gender"
You are mixing name attribute with ID.
An ID must always be unique : a web page can't contain several elements with the same ID.
What you are looking for is the checked input of name "gender".
var genderValue = '';
document.querySelectorAll('input[name=gender]').forEach((e)=>{
if (e.checked==true) { genderValue = e.value; }
});

Couple of mistakes you did:
Radio buttons and Checkboxes should always have same name if they are in the same group.
Always keep ID different, its bad practice to keep ID same for multiple elements.
When you are trying to get the value of Radio button or Checkboxes, fetch it using getElementsByName and run a loop over all on click of display button not outside.
Safer side and to reduce the LOC, give your form an ID and reset the form on submit using formId.reset() method. (in your code I have given form an id myForm so I have added myForm.reset(); at the end of the code on submit method)
See the Snippet below:
(function setup() {
"use strict";
var myForm = document.getElementById("myForm");
var NameElem = document.getElementById("name");
var ageElem = document.getElementById("age");
var genderElem = document.getElementsByName('gender');
var languageElem = document.getElementsByName("language");
var tableElem = document.getElementById("table");
var selectedGender = '';
var selectedLanguages = [];
document.addEventListener("click", function(event){
if(event.target.classList.contains("delete")){
var row = event.target.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
document.getElementById("display").addEventListener("click", function() {
for(var i = 0; i < genderElem.length; i++) {
if(genderElem[i].checked)
selectedGender = genderElem[i].value;
}
for(var i = 0; i < languageElem.length; i++) {
if(languageElem[i].checked)
selectedLanguages.push(languageElem[i].value);
}
var newRow = tableElem.insertRow(-1);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(NameElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(1);
newText = document.createTextNode(selectedGender);
newCell.appendChild(newText);
newCell = newRow.insertCell(2);
newText = document.createTextNode(ageElem.value);
newCell.appendChild(newText);
newCell = newRow.insertCell(3);
newText = document.createTextNode(selectedLanguages.toString());
newCell.appendChild(newText);
newCell = newRow.insertCell(4);
var deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.classList.add("delete");
newCell.appendChild(deleteBtn);
/*NameElem.value = "";
genderElem.value = "";
ageElem.value = "";
languageElem.value = "";
tableElem.value = "";*/
myForm.reset();
selectedGender = "";
selectedLanguages = [];
});
})();
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="container">
<br>
<br>
<h3 class="text-center">Display answers of form fill in inside a table</h3>
<br>
<br>
<form id="myForm">
<div class="form-group">
<label>First Name</label>
<input id="name" class="form-control form-control-sm" />
</div>
<div class="form-group">
<label>Age</label>
<input id="age" class="form-control form-control-sm" />
</div>
<div class="form-group">
Gender:<input type="radio" name="gender" id="male" value="Male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female" value="Female">
<label for="female">Female</label>
</div>
<div class="form-group">
<label>Language</label>
<input type="checkbox" id="malayalam" name="language" value="Malayalam">Malayalam
<input type="checkbox" id="english" name="language" value="English">English
<input type="checkbox" id="hindi" name="language" value="Hindi">Hindi
</div>
<button type="button" id="display" class="btn btn-sm btn-primary">Display</button>
</form>
<br>
<br>
<table class="table border" id="table">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Language</th>
<th>Action</th>
</tr>
</table>
<script type="text/javascript" src="form.js"></script>
</div>
UPDATE 1 : Added delete row feature
document.addEventListener("click", function(event){
if(event.target.classList.contains("delete")){
var row = event.target.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
newCell = newRow.insertCell(4);
var deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.classList.add("delete");
newCell.appendChild(deleteBtn);

Related

Data inserted into a form disappears on form submit

I'm trying to insert data through the following JavaScript code. The data inserted, however, disappears from the table when I click Submit.
Here's my code:
let myform = document.querySelector("form");
let myFN = document.getElementById("fname");
let myLN = document.getElementById("lname");
let MyPar = document.querySelector("p");
let submit = document.getElementById("submit");
myform.addEventListener("submit", (e) => {
if (myFN.value === "" || myLN.value === "") {
e.preventDefault();
MyPar.textContent = 'you need to fill all';
}
});
myform.addEventListener("submit", function() {
document.getElementById("table").style.display = "block";
// trigger the table form page
let table = document.getElementById("table");
let row = table.insertRow(-1);
let fname1 = row.insertCell(0);
let lname1 = row.insertCell(1);
fname1.innerHTML = document.getElementById("fname").value;
lname1.innerHTML = document.getElementById("lname").value;
});
table {
display: none;
}
table,
td {
border: 1px solid black;
}
<form>
<div>
<label for="fname">First name: </label>
<input id="fname" type="text" />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text" />
</div>
<div>
<input id="submit" type="submit" />
</div>
</form>
<p></p>
<table id="table">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</table>
First, you should remove the event listener that checks whether or not the input fields are blank. You instead can use required for the input tags in the HTML because it has a built-in form validation.
Then, all you need to do is remove the if statement around the e.preventDefault() so it is executed every time the button is clicked.
let myform = document.querySelector("form");
let myFN = document.getElementById("fname");
let myLN = document.getElementById("lname");
let MyPar = document.querySelector("p");
let submit = document.getElementById("submit");
myform.addEventListener("submit", (e) => {
e.preventDefault();
});
myform.addEventListener("submit", function() {
document.getElementById("table").style.display = "block";
// trigger the table form page
let table = document.getElementById("table");
let row = table.insertRow(-1);
let fname1 = row.insertCell(0);
let lname1 = row.insertCell(1);
fname1.innerHTML = document.getElementById("fname").value;
lname1.innerHTML = document.getElementById("lname").value;
});
table {
display: none;
}
table,
td {
border: 1px solid black;
}
<form>
<div>
<label for="fname">First name: </label>
<input id="fname" type="text" required />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text" required />
</div>
<div>
<button id="submit">Submit</button>
</div>
</form>
<table id="table">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</table>

How to prevent changes for radio button input for duplicated row

I'm a beginner in JavaScript. I have a table row which consist of text input, radio buttons and button to add or delete the row. When I click the add button, it will duplicate the row exactly like the current one. However, when I click any of the radio button in second row (the duplicated row), my choice from the first row is changed/cleared. How can I solved this? And how can I save and export this HTML form to excel?
I have tried all methods that I can find and even watched YouTube videos. Any suggestion to improve my code are welcome. Thank you.
function addRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i + 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i++)
inputs[i].value = "";
}
function delRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').deleteRow(i - 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i--)
inputs[i].value = "";
}
<div style="overflow-x:auto;">
<table id="Table" style="width: 100%">
<tr>
<td><input type="text" name="questions" size="80" id="questions" placeholder="Questions" required/><br><br>
<input type="radio" name="smiley" value="rd1">&#128542 I don't like it at all.<br>
<input type="radio" name="smiley" value="rd2">&#128533 I maybe like it.<br>
<input type="radio" name="smiley" value="rd3">&#128578 I like it.<br>
<input type="radio" name="smiley" value="rd4">&#128516 I like it very much.<br><br>
<input type="button" id="addBtn" value="Add Questions" onclick="addRow(this)" value="1" />
<input type="button" id="delBtn" value="Delete Questions" onclick="delRow(this)" value="1" />
</td>
</tr>
</table>
</div>
You can see how to download csv from html table here
As for your code, you need to change the name of the input for the new row.
function addRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i + 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML.replace(/smiley/g, "smiley" + i);
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i++)
inputs[i].value = "";
}
function delRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').deleteRow(i - 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i--)
inputs[i].value = "";
}
<div style="overflow-x:auto;">
<table id="Table" style="width: 100%">
<tr>
<td><input type="text" name="questions" size="80" id="questions" placeholder="Questions" required/><br><br>
<label><input type="radio" name="smiley" value="rd1">&#128542 I don't like it at all.</label><br>
<label><input type="radio" name="smiley" value="rd2">&#128533 I maybe like it.</label><br>
<label><input type="radio" name="smiley" value="rd3">&#128578 I like it.</label><br>
<label><input type="radio" name="smiley" value="rd4">&#128516 I like it very much.<br></label><br>
<input type="button" id="addBtn" value="Add Questions" onclick="addRow(this)" value="1" />
<input type="button" id="delBtn" value="Delete Questions" onclick="delRow(this)" value="1" />
</td>
</tr>
</table>
</div>
Different radio button groups need different names. I tweaked your JS to add a unique timestamp to the radio button name when adding a new row.
function addRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i + 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i++)
inputs[i].value = "";
const unique= Date.now();
const radios = tr.querySelectorAll("input[type='radio']");
for (var i = 0; i < radios.length; i++)
radios[i].name = `${radios[i].name}${unique}`;
}
function delRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').deleteRow(i);
}
<div style="overflow-x:auto;">
<table id="Table" style="width: 100%">
<tr>
<td><input type="text" name="questions" size="80" id="questions" placeholder="Questions" required/><br><br>
<input type="radio" name="smiley" value="rd1">&#128542 I don't like it at all.<br>
<input type="radio" name="smiley" value="rd2">&#128533 I maybe like it.<br>
<input type="radio" name="smiley" value="rd3">&#128578 I like it.<br>
<input type="radio" name="smiley" value="rd4">&#128516 I like it very much.<br><br>
<input type="button" id="addBtn" value="Add Questions" onclick="addRow(this)" value="1" />
<input type="button" id="delBtn" value="Delete Questions" onclick="delRow(this)" value="1" />
</td>
</tr>
</table>
</div>
I would delegate and clone
NOTE I changed the id to a class for the buttons and added a tbody
You must have unique IDs
I renumber all the radios from 1 to n even when you delete a row in the middle
I also hide the first delete using CSS
const tb = document.getElementById("Table");
const firstRow = tb.querySelector("tr")
tb.addEventListener("click", e => {
const tgt = e.target;
if (!tgt.type === "button") return; // not a button
if (tgt.matches(".addBtn")) tb.append(firstRow.cloneNode(true)); // clone the first row
else if (tgt.matches(".delBtn")) tgt.closest("tr").remove();
// rename radios
tb.querySelectorAll("tr").forEach((tr,i) => {
tr.querySelectorAll("input[type=radio]").forEach(rad => rad.name = `question${i+1}`)
})
})
#Table tr:first-child .delBtn { display: none; }
<div style="overflow-x:auto;">
<table style="width: 100%">
<tbody id="Table">
<tr>
<td><input type="text" name="questions" size="80" placeholder="Questions" required/><br><br>
<input type="radio" name="question1" value="rd1">&#128542 I don't like it at all.<br>
<input type="radio" name="question1" value="rd2">&#128533 I maybe like it.<br>
<input type="radio" name="question1" value="rd3">&#128578 I like it.<br>
<input type="radio" name="question1" value="rd4">&#128516 I like it very much.<br><br>
<input type="button" class="addBtn" value="Add Questions" value="1" />
<input type="button" class="delBtn" value="Delete Questions" value="1" />
</td>
</tr>
</tbody>
</table>
</div>

How can i get multiple input values with javascript

I tried to code a student manager like below. But when i ran my code in web there seem something error that i dont understanding. I can't get input value from gender and language. When i check console to see something wrong in my code, just a blank.So i dont know why i can't get value when i didn't get any error from console. Because my english skill is not good so I can't explain my mistake. i'm sorry for that. Can someone help me. Thanks firstenter image description here
<table>
<form onsubmit="event.preventDefault();onFormSubmit();" autocomplete="off">
<div id="s1">
<label>Student Name:</label>
<input type="text" placeholder="Input student name"
title="Please fill out this field" id="name" name="name">
</div>
<div id="s2">
<label>Student DOB:</label>
<input type="date" placeholder="dd-mm-yyyy" id="date" name="date">
</div>
<div id="s3">
<label>Student gender:</label>
<input type="radio" id="gender1" class="gender" name="gender">Male
<input type="radio" id="gender2" class="gender" name="gender">Female
</div>
<div id="s4">
<label>Student Language</label>
<input type="checkbox" id="lang1" class="lang" name="lang">English
<input type="checkbox" id="lang2" class="lang" name="lang">Vietnamese
<input type="checkbox" id="lang3" class="lang" name="lang">Japanese
<input type="checkbox" id="lang4" class="lang" name="lang">Chinese
<input type="checkbox" id="lang5" class="lang" name="lang">French
</div>
<div id="s5">
<label>Student Class:</label>
<select id="class" name="class">
<option>C1608G</option>
</select>
Add class
</div>
<button id="bt">Add</button>
</form>
<br><br><br>
<h2><strong>Student List</strong></h2>
<br>
<table id="table" border="1">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>DOB</th>
<th>Gender</th>
<th>Language</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is my javascript code
var selectedRow = null
function onFormSubmit() {
var formData = readFormData();
// check empty row
if (selectedRow == null) {
// Insert New User Record
insertNewRecord(formData);
}
else {
// Update New User Record
updateRecord(formData);
}
// Reset Input Values
resetForm();
}
function readFormData() {
var formData = {};
// Get Values From Input
formData["name"] = document.getElementById("name").value;
formData["class"] = document.getElementById("class").value;
formData["date"] = document.getElementById("date").value;
formData["gender"] = document.getElementsByClassName("gender").value;
formData["lang"] = document.getElementsByClassName("lang").value;
// return Form Data
return formData;
}
function insertNewRecord(data) {
var table = document.getElementById("table").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.name;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.class;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.date;
cell4 = newRow.insertCell(3);
cell4.innerHTML = data.gender;
cell5 = newRow.insertCell(4);
cell5.innerHTML = data.lang;
cell5 = newRow.insertCell(5);
cell5.innerHTML = 'Delete';
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.date;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
function resetForm() {
document.getElementById("name").value = "";
document.getElementById("class").value = "";
document.getElementById("date").value = "";
document.getElementsByClassName("gender").value = "";
document.getElementsByClassName("lang").value = "";
selectedRow = null;
}
function onDelete(td) {
if (confirm('Are you sure to delete this record ?')) {
row = td.parentElement.parentElement;
document.getElementById("table").deleteRow(row.rowIndex);
resetForm();
}
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.data;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
Two major problems you have in your code.
Your radio/checkboxes need to have values - your code cannot infer the text next to them as the value (without some additional coding and anyways that's not the right way to do it)
To check which radio is selected, you can use querySelector and the ? flag. Here's what it looks like in your code after I've added it:
formData["gender"] = document.querySelector(".gender:checked")?.value || '';
Which is: document.querySelector(".gender:checked") finds the item with the class name 'gender' that is checked (the psuedo class :checked does that). If it doesn't exist (if there isn't an element with that class name or none of them are checked), the ? flag captures that and instead a blank value is used. (Otherwise it might throw an error or be undefined)
To get all the checked checkboxes, you can use this kind of structure:
formData["lang"] = [];
// creates the array
document.querySelectorAll(".lang:checked").forEach(item => formData["lang"].push(item.value));
// loops through each checked checkbox and gets it's value, adding it to the array
formData["lang"] = formData["lang"].join(', ')
// this converts your array into a list that is comma separated. This line is optional because javascript will show your array as a comma separated list anyways
var selectedRow = null
function onFormSubmit() {
var formData = readFormData();
// check empty row
if (selectedRow == null) {
// Insert New User Record
insertNewRecord(formData);
} else {
// Update New User Record
updateRecord(formData);
}
// Reset Input Values
resetForm();
}
function readFormData() {
var formData = {};
// Get Values From Input
formData["name"] = document.getElementById("name").value;
formData["class"] = document.getElementById("class").value;
formData["date"] = document.getElementById("date").value;
formData["gender"] = document.querySelector(".gender:checked")?.value || '';
formData["lang"] = [];
document.querySelectorAll(".lang:checked").forEach(item => formData["lang"].push(item.value));
formData["lang"] = formData["lang"].join(', ')
// return Form Data
return formData;
}
function insertNewRecord(data) {
var table = document.getElementById("table").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.name;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.class;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.date;
cell4 = newRow.insertCell(3);
cell4.innerHTML = data.gender;
cell5 = newRow.insertCell(4);
cell5.innerHTML = data.lang;
cell5 = newRow.insertCell(5);
cell5.innerHTML = 'Delete';
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.date;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
function resetForm() {
document.getElementById("name").value = "";
document.getElementById("class").value = "";
document.getElementById("date").value = "";
document.getElementsByClassName("gender").value = "";
document.getElementsByClassName("lang").value = "";
selectedRow = null;
}
function onDelete(td) {
if (confirm('Are you sure to delete this record ?')) {
row = td.parentElement.parentElement;
document.getElementById("table").deleteRow(row.rowIndex);
resetForm();
}
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.name;
selectedRow.cells[1].innerHTML = formData.class;
selectedRow.cells[2].innerHTML = formData.data;
selectedRow.cells[3].innerHTML = formData.gender;
selectedRow.cells[4].innerHTML = formData.lang;
}
<form onsubmit="event.preventDefault();onFormSubmit();" autocomplete="off">
<div id="s1">
<label>Student Name:</label>
<input type="text" placeholder="Input student name" title="Please fill out this field" id="name" name="name">
</div>
<div id="s2">
<label>Student DOB:</label>
<input type="date" placeholder="dd-mm-yyyy" id="date" name="date">
</div>
<div id="s3">
<label>Student gender:</label>
<input type="radio" id="gender1" class="gender" name="gender" value="Male">Male
<input type="radio" id="gender2" class="gender" name="gender" value="Female">Female
</div>
<div id="s4">
<label>Student Language</label>
<input type="checkbox" id="lang1" class="lang" name="lang" value="English">English
<input type="checkbox" id="lang2" class="lang" name="lang" value="Vietnamese">Vietnamese
<input type="checkbox" id="lang3" class="lang" name="lang" value="Japanese">Japanese
<input type="checkbox" id="lang4" class="lang" name="lang" value="Chinese">Chinese
<input type="checkbox" id="lang5" class="lang" name="lang" value="French">French
</div>
<div id="s5">
<label>Student Class:</label>
<select id="class" name="class">
<option>C1608G</option>
</select>
Add class
</div>
<button id="bt">Add</button>
</form>
<br><br><br>
<h2><strong>Student List</strong></h2>
<br>
<table id="table" border="1">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>DOB</th>
<th>Gender</th>
<th>Language</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

How do I set the values of cells in a table to be values of a text input onclick using javascript?

I am trying to be able to display data in text inputs and a select input from an existing table, that on click of an edit button (one for each row), the data is inserted. I also want it to use the this function (which I'm not confident using) so that only data from the row that is clicked on, is inputted into the text inputs. Currently the values are showing up as undefined. Sorry about the messy code.
function displayStudent(student) {
let newStudent =
`<tr>
<td>${student.firstName}</td>
<td>${student.lastName}</td>
<td>${student.grade}</td>
<td>${student.email}</td>
<td><input type="button" value="EDIT" class="editButton" onclick="editStudent(this)"></td>
</tr>`;
document.getElementById('studentTable').innerHTML += newStudent;
}
function editStudent() {
document.getElementById("firstName").value = this.document.getElementsByTagName("td")[0].value;
document.getElementById("lastName").value = this.document.getElementsByTagName("td")[1].value;
document.getElementById("grade").value = this.document.getElementsByTagName("td")[2].value;
document.getElementById("email").value = this.document.getElementsByTagName("td")[3].value;
}
<table id="studentTable">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Grade</th>
<th>Email</th>
</tr>
</table>
<div id="editFields">
<div class="fields">
<label for="firstName">First Name</label>
<input id="firstName" type="text">
</div>
<div class="fields">
<label for="lastName">Last Name</label>
<input id="lastName" type="text">
</div>
<div class="fields">
<label for="grade">Grade</label>
<select id="grade">
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<div class="fields">
<label for="email">Email</label>
<input id="email" type="text">
</div>
Please do not pass this, pass event and you can get the details of current row and fill the inputs
<td><input type="button" value="EDIT" class="editButton" onclick="editStudent(event)"></td>
function editStudent(e) {
e.preventDefault();
document.getElementById("firstName").value = e.target.parentElement.parentElement.children[0].textContent;
document.getElementById("lastName").value = e.target.parentElement.parentElement.children[1].textContent;
document.getElementById("grade").value = e.target.parentElement.parentElement.children[2].textContent;
document.getElementById("email").value = e.target.parentElement.parentElement.children[3].textContent;
}
I've prepared a more detailed example with ids being generated dynamically and button's name and "onclick" function content changing according to action.
Here also is the codepen view which I've used to edit it:
https://codepen.io/antiqtech/pen/YzZaKGJ
<table id="studentTable">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Grade</th>
<th>Email</th>
</tr>
</table>
<div id="editFields">
<div class="fields">
<label for="firstName">First
Name</label>
<input id="firstName"
type="text">
</div>
<div class="fields">
<label for="lastName">Last Name</label>
<input id="lastName" type="text">
</div>
<div class="fields">
<label for="grade">Grade</label>
<select id="grade">
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<div class="fields">
<label for="email">Email</label>
<input id="email" type="text">
</div>
<button type="button" id="btnEditUpdate"
onclick="insertStudent();">Insert</button>
function insertStudent() {
var student = { firstName: "", lastName: "", grade: "",
email: "" };
student.firstName =
document.getElementById("firstName").value;
student.lastName = document.getElementById("lastName").value;
student.grade = document.getElementById("grade").value;
student.email = document.getElementById("email").value;
displayStudent(student);
}
function displayStudent(student)
{
var cc = Math.random();
let newStudent =
`<tr>
<td id="fn_` +
cc +
`">${student.firstName}</td>
<td id="ln_` +
cc +
`">${student.lastName}</td>
<td id="gr_` +
cc +
`">${student.grade}</td>
<td id="em_` +
cc +
`">${student.email}</td>
<td><input type="button" value="EDIT"
class="editButton"
onclick="editStudent(` +
cc +
`)"></td>
</tr>`;
document.getElementById("studentTable").innerHTML +=
newStudent;
document.getElementById("firstName").value = "";
document.getElementById("lastName").value = "";
document.getElementById("grade").value = "";
document.getElementById("email").value = "";
}
function editStudent(val)
{
document.getElementById("firstName").value =
document.getElementById(
"fn_" + val).innerHTML;
document.getElementById("lastName").value =
document.getElementById(
"ln_" + val).innerHTML;
document.getElementById("grade").value =
document.getElementById(
"gr_" + val).innerHTML;
document.getElementById("email").value =
document.getElementById(
"em_" + val).innerHTML;
document.getElementById("btnEditUpdate").onclick = function
() {
updateStudent(val);
};void 0;
document.getElementById("btnEditUpdate").innerHTML =
"Update";
}
function updateStudent(val)
{
document.getElementById("fn_" + val).innerHTML =
document.getElementById(
"firstName").value;
document.getElementById("ln_" + val).innerHTML =
document.getElementById(
"lastName").value;
document.getElementById("gr_" + val).innerHTML =
document.getElementById(
"grade").value;
document.getElementById("em_" + val).innerHTML =
document.getElementById(
"email").value;
document.getElementById("firstName").value = "";
document.getElementById("lastName").value = "";
document.getElementById("grade").value = "";
document.getElementById("email").value = "";
document.getElementById("btnEditUpdate").onclick = function ()
{
insertStudent();
};
document.getElementById("btnEditUpdate").innerHTML =
"Insert";
}

calculating input values using javascript ( new fields )

<script>
var ex=1;
function add1(){
a1=Number(document.form.present_+ex.value);
a2=Number(document.form.total_+ ex.value);
g1=(a1/a2)*100;
document.form. percentage_ex. value=g1;
}
</script>
<script language="javascript" type="text/javascript" >
var ex=1;
function Add() {
var tbl = document.getElementById('tab');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var e=document.createElement('input');
e.type='text';
e.name='register_'+ex;
e.id='register_'+ex;
e.placeholder='Register Num';
e.className='form-control';
firstCell.appendChild(e);
var secondCell = row.insertCell(1);
var eve=document.createElement('input');
eve.type='text';
eve.name='present_'+ex;
eve.id='present_'+ex;
eve.placeholder='Present Hours';
eve.className='form-control';
secondCell.appendChild(eve);
var thirdCell = row.insertCell(2);
var e1 = document.createElement('input');
e1.type='text';
e1.name='total_'+ex;
e1.id='total_'+ex;
e1.placeholder='Total Hours';
e1.className='form-control';
thirdCell.appendChild(e1);
var fourthCell = row.insertCell(3);
var e2 = document.createElement('input');
e2.type='text';
e2.name='percentage_'+ex;
e2.id='percentage_'+ex;
e2.placeholder='Percentage';
e2.readOnly="true"
e2.className='form-control';
fourthCell.appendChild(e2);
ex++;
sampleform.ex.value=ex;
}
</script>
<form action="" method="post" name="sampleform">
<table id="tab" class="table table-responsive"
<tr>
<td><input type="text" name="register_0" id="register_0" placeholder="Register Num" class="form-control" required></td>
<td><input type="text" name="present_0" id="present_0" placeholder="Present Hours" class="form-control" autocomplete="off" ></td>
<td>
<input type="text" name="total_0" id="total_0" placeholder="Total Hours" class="form-control" autocomplete="off" >
</td>
<td>
<input type="text" name="percentage_0" id="percentage_0" placeholder="Percentage" class="form-control" autocomplete="off" readonly>
</td>
<td><button type="button" name="add" onclick="Add();" class="btn btn-block btn-sm" width="50px;">ADD</button></td>
</tr>
</table>
</center>
<lable>
<input name="ex" type="hidden" id="ex" value="1">
</lable>
<br />
<button type="button" onclick="javascript:add1();" class=" btn btn-info">Cal..</button>
<input type ="submit" name="submit" value="submit" class="btn btn-danger">
</center>
</form>
Output screen . Percentage calculation is displayed blank.
I am not perfect in Javascript.. I want to show percentage entered in an input box in next input box named percentage. Can anyone help me to figure it out?
I edited your script. Use document.forms['formname']['formvalue'].
Eg: document.forms['sampleform']['present_'+ex]
And change the "ex" variable to 0, because fields have name 'present_0', 'total_0' ...
var ex=0;
function add1(){
a1=Number(document.forms['sampleform']['present_'+ex].value);
a2=Number(document.forms['sampleform']['total_'+ex].value);
g1=(a1/a2)*100;
document.forms['sampleform']['percentage_' + ex].value=g1;
}
UPDATE: fixed Add() function:
function Add() {
ex++; //this must be executed at the beginning.
var tbl = document.getElementById('tab');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var e=document.createElement('input');
e.type='text';
e.name='register_'+ex;
e.id='register_'+ex;
e.placeholder='Register Num';
e.className='form-control';
firstCell.appendChild(e);
var secondCell = row.insertCell(1);
var eve=document.createElement('input');
eve.type='text';
eve.name='present_'+ex;
eve.id='present_'+ex;
eve.placeholder='Present Hours';
eve.className='form-control';
secondCell.appendChild(eve);
var thirdCell = row.insertCell(2);
var e1 = document.createElement('input');
e1.type='text';
e1.name='total_'+ex;
e1.id='total_'+ex;
e1.placeholder='Total Hours';
e1.className='form-control';
thirdCell.appendChild(e1);
var fourthCell = row.insertCell(3);
var e2 = document.createElement('input');
e2.type='text';
e2.name='percentage_'+ex;
e2.id='percentage_'+ex;
e2.placeholder='Percentage';
e2.readOnly="true"
e2.className='form-control';
fourthCell.appendChild(e2);
sampleform.ex.value=ex;
}
JsFiddle: https://jsfiddle.net/8h3rv3jh/1/

Categories