Deleting dynamically created rows with a checked checkbox via Javascript - javascript

I'm trying to delete rows that I created in JS which were created with the following code:
function createRow() {
var table = document.getElementById("appointment-table")
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
var cell4 = row.insertCell(3)
var cell5 = row.insertCell(4)
var cell6 = row.insertCell(5)
var checkbox = document.createElement("input")
checkbox.type = "checkbox"
checkbox.name = "name"
checkbox.value = "value"
checkbox.id = "id"
cell1.appendChild(checkbox)
cell2.innerHTML = document.getElementById("name").value
cell3.innerHTML = document.getElementById("email").value
cell4.innerHTML = document.getElementById("address").value
cell5.innerHTML = document.getElementById("phone").value
console.log(table)
var rows = table.getElementsByTagName("tr")
for (var i = 0; i \<= rows.length; i++) {
if (i % 2 == 0) {
rows\[i\].style.backgroundColor = "#F5F5F5"
} else {
rows\[i\].style.backgroundColor = "#FFFFFF"
}
}
return table
}
and I activate that by clicking a button which opens a form for those inputs.
This was my attempt to read the checked inputs but for some reason it's not able to read rows.
function removeSelected(table) {
for (var rowi = table.rows.length; rowi-- \> 0; ) {
var row = table.rows\[rowi\]
var inputs = row.getElementsByTagName("input")
for (var inputi = inputs.length; inputi-- \> 0; ) {
var input = inputs\[inputi\]
if (input.type === "checkbox" && input.checked) {
row.parentNode.removeChild(row)
break
}
}
}
}
here is my remove button
<a href="#deleteEmployeeModal" class="btn btn-danger" data-toggle="modal" onclick="removeSelected()"><i class="material-icons"></i>
<span>Remove patient</span></a>
here is my create patient
<div class="form-popup" id="myForm">
<form action="/action_page.php" class="form-container">
<h2>Add a new Appointment</h2>
<label for="Name"><b>Patient Name</b></label>
<input id="name" type="text" placeholder="Enter Name" name="name" required>
<label for="Email"><b>Email Address</b></label>
<input id="email" type="text" placeholder="Enter Email Address" name="email" required>
<label for="Address"><b>Address</b></label>
<input id="address" type="text" placeholder="Enter Address" name="address" required>
<label for="Phone"><b>Phone Number</b></label>
<input id="phone" type="text" placeholder="Enter Phone Number" name="phone" required>
<label for="N/a"><b></b></label>
<input id="blank" type="text" placeholder="" name="" required>
<button type="submit" onclick="createRow()" class="btn">Add Appointment</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
nothing works ever for me

Related

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 to display radio and checkbox values in table using 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);

JavaScript and HTML Passing ID Values when Adding NewCell

I'm using the ID of an inputs to get its total, the ID is name "qty", this worked when I was working with input boxes. But then when I switched to tables, which cells are entered via javascript. It wouldn't work. HI have three questions
Here's my code:
my javascript:
function addRow()
{
var table = document.getElementById("datatable"),
newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
name = document.getElementById("form").value,
amount = document.getElementById("amount").value;
delete1 = delete1 = '<input type="button" class="btn btn-danger" class="glyphicon glyphicon-trash"id="delete" value="Delete" onclick="deleteRow(this)">';
cell1.innerHTML = name;
cell2.innerHTML = amount;
cell3.innerHTML = delete1;
}
my HTML:
<h2>Type in Nature of Collection...</h2>
<form>
<input class="form-control input-lg" id="form" list="languages" placeholder="Search" type="text" required>
<br>
<input class="form-control input-lg" id="amount" list="languages" placeholder="Amount" type="number" required>
<br>
<button onclick="addRow(); return false;">Add Item</button>
</form>
<h3><fieldset disabled>
<label>Total </label>
<input type = "text" name = "total" id="total"><br></p>
</fieldset></h3>
I have two questions
How do I add an ID for every cell inserted? as you can see on my javascript, I haven't added the id yet, but so far I tried.
var ID = 'qty'
cell2.id = newRow.ID
Thinking this would match my TOTAL Javascript which is:
<script type="text/javascript">
function findTotal(){
var arr = document.getElementByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
Which adds every amount where id is set to qty and displays it in the "total" input bat.
How do I fetch the values of all these values at once?
Thanks! Any help is appreciated!

javascript: submit button pulls all values from the textboxes and displays them in a p tag

So what I am trying to do here is when the submit button is clicked pull all of the values from the textboxes and display them in a p tag that I have on my html page. I have been tring to figure this out for days. Can somebody let me know what I am doing wrong?
/* JavaScript */
$("#submit").click(function(){
var doc = $("#doctorate").val()
var Name = $("#first_name").val();
var Last = $("#last_name").val();
var T = Doc + " "+ Name + " " + Last
break
var Certs = $("#certs").val()
break
var Title = $("#title").val()
break
var Department = $("#department").val()
break
var Numb = $("#number").val()
break
var Web = $("#website").val()
break
var Ema = $("#email").val()
document.getElementById('output').innerHTML = T;
})
HTML unchanged
The big problem I see is that you keep assigning the same thing to your output. Try something like this (reduced for brevity):
function myOut() {
var output = document.getElementById("certs").value;
output = output + document.getElementById("title").value;
if (certs != null) {
document.getElementById("output").innerHTML = output;
}
}
<input type="text" id="certs" />
<input type="text" id="title" />
<p id="output"></p>
<button onclick="myOut()">
Sub
</button>
Here you can try this one.
var role = document.getElementById("role").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var doctorate = document.getElementById("doctorate").value;
var certs = document.getElementById("certs").value;
var title = document.getElementById("title").value;
var department = document.getElementById("department").value;
var number = document.getElementById("number").value;
var website = document.getElementById("website").value;
var email = document.getElementById("email").value;
var output = document.getElementById("output").value;
$("#submit").click(function(){
var N = $("#first_name").val();
var L = $("#last_name").val();
var T = N + " " + L;
if (doctorate.checked) {
document.getElementById('output').innerHTML = T;
}
if (first_name != null) {
document.getElementById('output').innerHTML = T;
}
if (last_name != null) {
document.getElementById('output').innerHTML = T;
}
if (certs != null) {
document.getElementById('output').innerHTML = T;
}
if (title != null) {
document.getElementById('output').innerHTML = T;
}
if (department != null) {
document.getElementById('output').innerHTML = T;
}
if (number != null) {
document.getElementById('output').innerHTML = T;
}
if (website != null) {
document.getElementById('output').innerHTML = T;
}
if (email != null) {
document.getElementById('output').innerHTML = T;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset id="role">
<legend>My Role</legend>
<label for="faculty">
<input type="radio" name="role" id="faculty" value="faculty" />
Faculty
</label>
<label for="staff">
<input type="radio" name="role" id="staff" value="staff" />
Staff
</label>
</fieldset>
<fieldset id="userinformation">
<legend>User Information</legend>
<label for="doctorate">
Doctorate?
<input type ="checkbox" id="doctorate" value="" />
</label>
<label>
First Name:
<input type="text" name="name" id="first_name" required />
</label>
<label>
Last Name:
<input type="text" name="name" id="last_name" required />
</label>
<label>
Certifications:
<input type="text" name="cert" id="certs" />
</label>
<label>
Title:
<input type="text" name="title" id="title" required />
</label>
<label>
Department:
<select id="department" required>
<option disabled selected value>-Select a Department-</option>
<option>School of Information Technology</option>
<option>Mathematics</option>
<option>English</option>
<option>History</option>
<option>Natural Sciences</option>
<option>Psychology</option>
<option>School of Health Sciences</option>
</select>
</label>
<label>
Primary Phone #:
<input type="tel" name="number" id="number" placeholder="444-123-1234" pattern="^\d{3}-\d{3}-\d{4}$"/>
</label>
<label>
Email:
<input type="email" name="email" id="email" placeholder="JDoe#example.com" required />
<span id="err3"></span>
</label>
<label>
Website:
<input type="text" name="website" id="website" placeholder="http//:www.example" pattern="https?://.+" />
</label>
</fieldset>
<fieldset id = "results">
<p id="output"></p>
</fieldset>
<fieldset id="submit_button">
<input type="button" id="submit" value="submit" />
</fieldset>

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