<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/
Related
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
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>
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);
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!
I'm a bit stuck with javascript again. Basically when you click a button a new row of fields will appear, giving them a new name just a different number.
I now need these fields to be able to auto sum by themself, i can do this with the first row I just don't know how to do them with the new generated ones.
The Javascript code:
<script language="javascript" type="text/javascript">
var i=2;
function addRow()
{
var tbl = document.getElementById('customersAdd');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.placeholder = 'Quantity';
el.type = 'text';
el.name = 'quantity' + i;
el.id = 'quantity' + i;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.placeholder = 'Description';
el2.type = 'text';
el2.name = 'description' + i;
el2.id = 'description' + i;
secondCell.appendChild(el2);
var thirdCell = row.insertCell(2);
var el3 = document.createElement('input');
el3.placeholder = 'Rate';
el3.type = 'text';
el3.name = 'rate' + i;
el3.id = 'rate' + i;
thirdCell.appendChild(el3);
var forthCell = row.insertCell(3);
var el4 = document.createElement('input');
el4.placeholder = 'Amount';
el4.type = 'text';
el4.name = 'amount' + i;
el4.id = 'amount' + i;
forthCell.appendChild(el4);
// alert(i);
i++;
// alert(i);
}
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.main.quantity1.value;
two = document.main.rate1.value;
document.main.amount1.value = (one * 1) * (two * 1);
}
function stopCalc(){
clearInterval(interval);
}
</script>
The HTML code:
<form action="submit.php" name="main" method="post">
<table style="border-collapse: collapse;" border="0" align="center" width="50%" class="horiz" id="customersAdd">
<tr>
<td align="center"><br/>
<input class="text" style="width:100%" type="button" align="middle"value="Add Aditional Row" onClick="addRow()" /></td>
</tr>
<tr align="center">
<td>
<br />
<input placeholder="Quantity" type="text" name="quantity1" id="quantity1" onFocus="startCalc();" onBlur="stopCalc();" />
<br /></td>
<td>
<br />
<input placeholder="Description" type="text" name="description1" id="description1"/>
<br /></td>
<td>
<br />
<input placeholder="Rate" type="text" name="rate1" id="rate1" onFocus="startCalc();" onBlur="stopCalc();"/>
<br /></td>
<td>
<br />
<input placeholder="Amount" type="text" name="amount1" id="amount1" onBlur="stopCalc();" onFocus="startCalc();" readonly="true" />
<br /></td>
</tr>
</table></form>
To make things easier for anyone who could help me I have made this in JSBin to see it easier of what i want to do. Any suggestions are appreciated.
http://jsbin.com/atabaz/1/edit
Thanks
In the end I managed to find a way on how to do this myself, if anyone is interested take a look at this:
http://jsfiddle.net/2sYgE/
var currentItem = 1;
$('#customersAdd').on('keyup', '.quantity, .rate, .amount', calculateRow);
$('#addnew').click(function() {
currentItem++;
$('#customersAdd').append('<tr><td><input placeholder="Quantity" type="text" name="quantity' + currentItem +'" id="quantity' + currentItem +'" class="qty form-input-rate" /></td><td><input placeholder="Description" type="text" name="description' + currentItem +'" id="description' + currentItem +'" class="form-input-rate"/></td><td><input placeholder="Rate" type="text" name="rate' + currentItem +'" id="rate' + currentItem +'" class="rate form-input-rate"/></td><td><input placeholder="Amount" type="text" name="amount' + currentItem +'" id="amount' + currentItem +'" class="cal form-input-rate"/></td></tr>'
);
});
function calculateSum() {
var sum = 0;
$(".cal").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
}
function calculateRow() {
var cost = 0;
var $row = $(this).closest("tr");
var qty = parseFloat($row.find('.qty').val());
// changed the following line to only look within the current row
var rate = parseFloat($row.find('.rate').val());
cost = qty * rate;
if (isNaN(cost)) {
$row.find('.cal').val("0");
} else {
$row.find('.cal').val(cost);
}
calculateSum();
}
Polling for changes is a very inefficient and error–prone way to do form updates. Listening for change events is a better way to go as it uses fewer resources and waits until the user has finished updating the control before doing anything. There is also an input event that can be used, but it's not suitable here as it will update the form as the user enters values. Much better to wait for the user to finish entering values, then do the update.
I've re–factored your code below, it's not ready for production but it should give you some idea of how to go about it. Table rows are cloned as it's much faster than creating all the elements from scratch. Then names are modified, though this isn't really necessary. There is no need for ID attributes.
Cloning only works reliably here if inline listeners are used on the form controls. If the initial listeners are dynamically attached, you'll have to add them each time a row is added as listeners added using addEventListener are not cloned.
I haven't included any input validation, if the user puts in junk, they get junk back. You should validate input to check that appropriate values are being entered, and also format the displayed values for presentation.
<script type="text/javascript">
function addRow(element) {
var form = element.form;
var table = form.getElementsByTagName('table')[0];
var tbody = table.tBodies[0];
var num = tbody.rows.length - 1;
var row = table.rows[1].cloneNode(true);
var input, inputs = row.getElementsByTagName('input')
// Update input names
for (var i=0, iLen=inputs.length; i<iLen; i++) {
input = inputs[i];
input.name = input.name.replace(/\d+$/,num);
input.value = '';
}
tbody.insertBefore(row, tbody.rows[tbody.rows.length - 1]);
}
function updateRow(element) {
var form = element.form;
var num = element.name.replace(/^\D+/,'');
var value = form['quantity' + num].value * form['rate' + num].value;
form['amount' + num].value = (value == 0)? '' : value;
updateTotal(form);
}
function updateTotal(form) {
var elements = form.elements;
var name = /^amount/;
var total = 0;
var value;
for (var i=0, iLen=elements.length; i<iLen; i++) {
if (name.test(elements[i].name)) {
total += parseFloat(elements[i].value);
}
}
form.total.value = total;
}
</script>
<form action="submit.php" name="main" method="post">
<table style="border-collapse: collapse;" border="0" align="center"
width="50%" class="horiz" id="customersAdd">
<tr>
<td><br>
<input class="text" style="width:100%" type="button"
align="middle"value="Add Aditional Row" onclick="addRow(this)">
</td>
</tr>
<tr>
<td>
<input placeholder="Quantity" name="quantity1" onblur="updateRow(this);">
</td>
<td>
<input placeholder="Description" type="text" name="description1">
</td>
<td>
<input placeholder="Rate" name="rate1" onchange="updateRow(this);">
</td>
<td>
<input placeholder="Amount" name="amount1" readonly>
</td>
</tr>
<tr>
<td colspan="3" style="text-align: right">Total
<td><input name="total" readonly>
</tr>
</table>
<input type="reset">
</form>