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!
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 searched but did not find, I want to implement something but unfortunately do not get it.
There are small components
How do I change the value of the position by 1 each time I add a new row.
How do I access the contents of the input fields without using a button? As an example, I want to display quantity * price and the value at total per row, it should work directly after the input, without using a button.
var table = document.getElementById("lineitems");
var row = table.insertRow();
var total = 0.00;
var cell = row.insertCell();
cell.innerHTML = '<input type="text" class="form-control" id="position" name="position[]" value="1">';
cell = row.insertCell();
cell.innerHTML = '<input type="text" class="form-control" id="service" name="service[]" placeholder="Produkt oder Service eingeben"><br><textarea class="form-control" name="description[]" rows="1" placeholder="Beschreibung"></textarea>';
cell = row.insertCell();
cell.innerHTML = '<input type="text" id="quantity" class="form-control" name="quantity[]" value="1">';
cell = row.insertCell();
cell.innerHTML = '<input type="text" class="form-control" id="unit" name="unit[]" placeholder="Einheit">';;
cell = row.insertCell();
cell.innerHTML = '<input type="text" class="form-control" id="price" name="example-text-input" name="price[]" placeholder="0,00">';
cell = row.insertCell();
cell.innerHTML = total;
}
<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/
i am creating a checkout page where users can purchase goods. i have managed to give each product its price but what I cant do is give them its quantity. i simply do no know how to do it. i created a quantity box for them but i can link the two.
my goal is to update the quantity and total price should be displayed on the checkout form.
since this is my homework for college, this must be done in strictly javascript if a solution arrives.
<script type="text/javascript">
function total(frm) {
var tot = 0;
for (var i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox") {
if (frm.elements[i].checked) tot += Number(frm.elements[i].value);
}
}
document.getElementById("totalDiv").firstChild.data = "£" + tot;
type = "text/javascript" > total(document.getElementById("theForm"));
}
</script>
<form action="nextpage" method="post" id="theForm">
<fieldset>
<legend>Choose your Products</legend>
<table style="padding:2px">
<tr>
<td>
<img src="http://placehold.it/200x200" />
</td>
<td>
<img src="http://placehold.it/200x200" />
</td>
<td>
<img src="http://placehold.it/200x200" />
</td>
<td>
<img src="http://placehold.it/200x200" />
</td>
</tr>
<tr>
<td class="buttons">
<div>
<input type="checkbox" name="r" value="25" onclick="total(this.form);" />£25</div>
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</td>
<td class="buttons">
<div>
<input type="checkbox" name="7" value="50" onclick="total(this.form);" />£50</div>
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</td>
<td class="buttons">
<div>
<input type="checkbox" name="asd7" value="75" onclick="total(this.form);" />£75</div>
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</td>
<td class="buttons">
<div>
<input type="checkbox" name="rasd7" value="100" onclick="total(this.form);" />£100</div>
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</td>
</tr>
</table>
<div id="totalDiv">£0</div>
<div>
<input type="submit" value="Place Order" />
</div>
</fieldset>
</form>
http://jsfiddle.net/isherwood/96qkr/
Simple and fast solution
Well the simplest solution would be:
Number(frm.elements[i].value) * Number(frm.elements[i+1].value);
Since the quantity element always comes AFTER the checkbox element.
The JavaScript then becomes:
function total(frm)
{
var tot = 0;
for (var i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox") {
if (frm.elements[i].checked) tot +=
Number(frm.elements[i].value) * Number(frm.elements[i+1].value);
}
}
document.getElementById("totalDiv").firstChild.data = "£" + tot;
}
You can see this works here.
To guarantee that the total div also gets updated when quantity is changed, you should add the onclick="total(this.form);" event to the class="quantity" input elements as well.
You can see how nicely this works here.
More advanced solution
Personally, I would use tabIndex to group the checkbox and quality inputs.
For example, for the first product:
<td class="buttons">
<div>
<input tabindex="1" name="checkbox" type="checkbox" value="25" onclick="total(this.form);" />£25</div>
<input tabindex="1" name="quantity" min="0" max="5" type="number" class="quantity" value="1" onclick="total(this.form);"/>
</td>
As you can see, I have explicitly defined the tabIndex and names.
Now for the JavaScript, I now use:
function total(frm)
{
var tot = 0;
var checkboxes = document.forms[frm.id].elements["checkbox"];
var quants = document.forms[frm.id].elements["quantity"];
for (var i = 0; i < checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
// if tabIndex correctly specified
if (checkboxes[i].tabIndex == quants[i].tabIndex)
// add to total
tot += Number(checkboxes[i].value) * Number(quants[i].value);
else
// notify of bug
alert('Bug in code: tabIndex of checkbox '+i+' is not the same as tabIndex quantity '+i);
}
}
document.getElementById("totalDiv").firstChild.data = "£" + tot;
}
By doing it this way you get the following advantages:
Your HTML code makes more sense (input elements are grouped per tabIndex)
Your code is checked for bugs
You are absolutely sure that you multiply the correct input elements
You can find this code in this jsFiddle.
Good luck! I hope this helps you out!
Update
To create a sort of checkout system, you could go over all the elements again and store them in a variable.
Then make sure that the form implements a function upon submit:
action="javascript:checkout()"
so in total:
<form action="javascript:checkout()" id="theForm">
Easiest way to create the message would be to use one variable like so:
function checkout()
{
var message = "";
var checkboxes = document.forms["theForm"].elements["checkbox"];
var quants = document.forms["theForm"].elements["quantity"];
for (var i = 0; i < checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
switch(checkboxes[i].tabIndex)
{
case 1: message += "iPhone"; break;
case 2: message += "Screen"; break;
case 3: message += "Laptop"; break;
case 4: message += "Coffee"; break;
default: message += "";
}
message += " Quantity: " + Number(quants[i].value) + " Price: £" + Number(checkboxes[i].value) * Number(quants[i].value) + "\n";
}
}
message += "\nTotal: " + document.getElementById("totalDiv").firstChild.data;
alert(message);
}
You can find a working implementation of this here.
Fancy solution
Or if you would like to make it a little bit more fancy, you could do the following:
Add the following HTML:
HTML
<br><br>
<div id="checkout">
<table id="myTable" border="1">
<tr>
<td>Product</td>
<td>Quantity</td>
<td>Price</td>
</tr>
</table>
</div>
Add the following JavaScript function:
JavaScript
function checkout()
{
document.getElementById("checkout").innerHTML = '<table id="myTable" border="1"><tr><td><b>Product</b></td><td><b>Quantity</b></td><td><b>Price</b></td></tr></table>';
// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");
var count = 0;
var max = 0;
var checkboxes = document.forms["theForm"].elements["checkbox"];
var quants = document.forms["theForm"].elements["quantity"];
for (var i = 0; i < checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
switch(checkboxes[i].tabIndex)
{
case 1: message = "iPhone"; break;
case 2: message = "Screen"; break;
case 3: message = "Laptop"; break;
case 4: message = "Coffee"; break;
}
count += Number(quants[i].value);
max += 1;
// Create an empty <tr> element and add it to the table:
var row = table.insertRow(max);
// Insert new cells (<td> elements) at the 1st, 2nd and 3rd position
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = message;
cell2.innerHTML = Number(quants[i].value);
cell3.innerHTML = "£" + Number(checkboxes[i].value) * Number(quants[i].value);
}
}
// Calculate total
var row = table.insertRow(max+1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "<b>Total</b>";
cell2.innerHTML = count;
cell3.innerHTML = document.getElementById("totalDiv").firstChild.data;
}
The result looks like this:
You can find the corresponding jsFiddle HERE.
Hope that helps you out!
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>