auto calculator each rows - javascript

I want to create a table that can auto calculate some values for each fields for each rows. I found these jquery calculator, I would like to ask how am I going to use it incase I'll be using jstl forEach, how can I use this so I would it can auto calculate what ever user entered on a field for each rows.. Thanks..
<html>
<head>
<script type="text/javascript" src="js/jquery-latest.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
$(document).ready(function()
{
$('input').change(function()
{
var ProductUnitVal = parseInt($('#product-unit-val').val());
var TotalUnitSales = parseInt($('#total-unit-sales').val());
var answer = ProductUnitVal * TotalUnitSales;
$('#sales-val').html('$' + answer);
});
});
</script>
</head>
<body>
Unit Value <input type="text" id="product-unit-val" /><br />
Unit Sales <input type="text" id="total-unit-sales" /><br />
<span id="sales-val"></span>
</body>
</html>

Make it row based. When an input changes, look for the closest row (tr) which finds the scope of the elements. Then search just that scope (i.e. the row) for the various elements. Note, I changed from id to class for the 3 items.
<table id="thetable">
<tr>
<td>
Unit Value <input type="text" class="product-unit-val" />
</td>
<td>
Unit Sales <input type="text" class="total-unit-sales" />
</td>
<td><span class="sales-val"></span></td>
</tr>
</table>
And then your script:
$(document).ready(function()
{
$('#thetable input').change(function()
{
var $row = $(this).closest('tr');
var ProductUnitVal = parseInt($row.find('.product-unit-val').val());
var TotalUnitSales = parseInt($row.find('.total-unit-sales').val());
var answer = ProductUnitVal * TotalUnitSales;
$row.find('.sales-val').html('$' + answer);
});
});

Related

Initially Hiding and then Dynamically Adding and Removing Rows

I'm working on a request form. It needs to list the study team members on a research study besides the PI and submitter of the form. However, some studies will have no additional team members so I would like the row to remain hidden until someone clicks the Add Team Member button.
What's working:
1. I've got the element hidden on initially loading the page.
2. Clicking add rows adds the correct rows.
3. Clicking remove will remove a row.
Current problems:
1. If someone adds a team member then removes all the team members, clicking add team member will not add a row.
2. When the element is hidden on initial page load, the first time the Add Team Member button is clicked it adds two rows.
Here's my current code with only the relevant section of the form.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="assets/css/test.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function addTableRow(jQtable){
jQtable.each(function(){
var tds = '<tr>';
jQuery.each($('tr:last td', this), function() {tds += '<td>'+$(this).html()+'</td>';});
tds += '</tr>';
if($('tbody', this).length > 0){$('tbody', this).append(tds);
}else {$(this).append(tds);}
});
}
</script>
<script>
function myDeleteFunction() {
document.getElementById("stmember").deleteRow(0);
}
</script>
<script type="text/javascript">
$(function() {
$('#add').click(function() {
$('#stmember').show();
});
});
</script>
<style>
#stmember {
display: none
}
</style>
</head>
<body>
<h3><strong>Other Study Team Members:</strong></h3>
<FORM>
<table id="stmember">
<tr>
<td>Name:
<label for="namest1"></label>
<input type="text" name="namest1" id="namest1" placeholder="First Name, Last Name" />
</td>
<td>JHED ID:
<label for="jhedst1"></label>
<input type="text" name="jhedst1" id="jhedst1" />
</td>
<td>Email:
<label for="emailst1"></label>
<input type="email" name="emailst1" id="emailst1" placeholder="you#example.com" />
</td>
</tr>
</table>
<CENTER>
<button type="button" id="add" onclick="addTableRow($('#stmember'));">Add Study Team Member</button>
<button type="button" onclick="myDeleteFunction()">Remove Study Team Member</button>
</CENTER>
</FORM>
</body>
</HTML>
Here are a couple solutions for you:
Solution 1
Store the HTML of the row in your addTableRow function within a variable. That way you can use tokens for the input IDs to ensure they are unique. Also, you won't have to provide the first row in your HTML, as it will be created through your JS function. Something like:
var template = "<tr><td>Name:<label for="namest1"></label><input type="text" name="namest!!TOKEN!!" id="namest!!TOKEN!!" placeholder="First Name, Last Name" /></td><td>JHED ID:<label for="jhedst1"></label><input type="text" name="jhedst!!TOKEN!!" id="jhedst!!TOKEN!!" /></td><td>Email:<label for="emailst1"></label><input type="email" name="emailst!!TOKEN!!" id="emailst!!TOKEN!!" placeholder="you#example.com" /></td></tr>";
Solution 2
Use a templating engine like jsRender or Mustache.
Conclusion
The cleanest method would be to use a templating engine, if you're game for that. But using a string to store the template within your function will work.
If you're using jQuery, I'd fully commit to using that instead of mixing vanilla JS, as with jQuery you can use clone and remove effectively for what you're trying to achieve. Also, if you plan on submitting this as a form, please be sure to add [] to your input names so you can parse each row properly as the names are the same on the input fields. Please see the below snippet:
function addTableRow() {
var $tableRow = $('tr.model-row:first-child');
var $clonedRow = $tableRow.clone().show();
$('#stmember').append($clonedRow);
}
function myDeleteFunction() {
var $memberTRs = $('tr', '#stmember');
// If rowcount === 1, hide first row, don't remove it!!
var rowCount = $memberTRs.length;
if (rowCount === 1) {
$('tr.model-row:first-child').hide();
return;
}
$memberTRs.last().remove();
}
jQuery(function() {
$('#delete').click(function() {
myDeleteFunction();
});
$('#add').click(function() {
addTableRow();
});
});
.model-row {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h3><strong>Other Study Team Members:</strong></h3>
<FORM>
<table id="stmember">
<tbody>
<tr class="model-row">
<td>Name:
<label for="namest1"></label>
<input type="text" name="namest1[]" id="namest1" placeholder="First Name, Last Name" />
</td>
<td>JHED ID:
<label for="jhedst1"></label>
<input type="text" name="jhedst1[]" id="jhedst1" />
</td>
<td>Email:
<label for="emailst1"></label>
<input type="email" name="emailst1[]" id="emailst1" placeholder="you#example.com" />
</td>
</tr>
</tbody>
</table>
<CENTER>
<button type="button" id="add">Add Study Team Member</button>
<button type="button" id="delete">Remove Study Team Member</button>
</CENTER>
</FORM>
</body>
When you create a row, you use the last existing row to create it. But if you remove all the row you lose your example of row.
You can easily fix your problem by checking when you remove a Row, if it's the last one, add a new row before remove the last one.

jQuery remove too many fields

I am creating a form where the user can add fields one after the other. For each field I am setting a "remove" button. Each field is in a table, so I give a random id to the table, and pass this id to a removing function doing: $(random-id).remove().
The strange thing is that jQuery is removing all of the tables created by the user, as if the id is not taken into account
Why that can be?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
function delete_field(id)
{
$("#"+id+"").remove();
}
function add_form_field()
{
id = Math.random();
html = '<table id='+id+'>\
<tr><td>Label </td></tr>\
</table>\
\
<button onclick=delete_field('+id+')>remove</button>';
$("form").append(html);
}
</script>
</head>
<body>
<form>
</form>
<button onclick=add_form_field()> Add a field </button>
</body>
</html>
Don't use Math.random, rather increment a number and create ID like: #tab_NN.
Add an ID to your Form Element id=myForm
Delegate click events to dynamically generated delete buttons using .on()
While removing the table that matched the button data-* attribute, delete the button too using .add( this ) (where this stays for the clicked button)
var id = 0;
function delete_field(event){
event.preventDefault();
$("#tab_"+ $(this).data("remove")).add(this).remove();
}
function add_form_field(){
id += 1;
var html = '<table id="tab_'+ id +'">'+
'<tr><td>Label</td></tr>'+
'</table>'+
'<button data-remove="'+id+'" class="remove">remove</button>';
$("#myForm").append(html);
}
$('#addField').on('click', add_form_field);
$('#myForm').on('click', '.remove', delete_field);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm"></form>
<button id="addField"> Add a field </button>
The code above allows you to have changes in the future markup cause it targets a specific ID, but in case your DELETE buttons will always be exactly after table than you can do it without assigning ID's, by simply using .prev("table"):
http://jsbin.com/wuqati/1/edit
function delete_field(event){
event.preventDefault();
$(this).prev("table").add(this).remove();
}
function add_form_field(){
var html = '<table>'+
'<tr><td>Label</td></tr>'+
'</table>'+
'<button class="remove">remove</button>';
$("#myForm").append(html);
}
$('#addField').on('click', add_form_field);
$('#myForm').on('click', '.remove', delete_field);
Math.random() produces a floating point number less than 1 which is invalid for an id. You can use a global variable to keep count of the rows created. Keep in mind that a CSS ID can not start with a digit. So append the number to a string before using it as an ID.
<script>
function delete_field(id)
{
$("#"+id+"").remove();
}
tableID = 1;
function add_form_field()
{
id = 'table-'+tableID;
html = '<table id='+id+'>\
<tr><td>Label </td></tr>\
</table>\
\
<button onclick=delete_field('+id+')>remove</button>';
$("form").append(html);
tableID++;
}
</script>
Why not simplify this by doing something like below.
$(".remover").click(function() {
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" placeholder="input One"/> <input type="button" class="remover" value="remove" />
</td> </tr>
<tr>
<td>
<input type="text" placeholder="input Two"/> <input type="button" class="remover" value="remove" />
</td> </tr>
<tr>
<td>
<input type="text" placeholder="input Three"/> <input type="button" class="remover" value="remove" />
</td> </tr>
</table>

Dynamic Fields js/php to MySql need to submit dynamically to the database

I can not get the values from the javascript add row to go dynamically as a row into MySql only the form values show up as the form below as one row. I made it as an array, but no such luck, I have tried this code around a multitude of ways. I don't know what I am doing wrong, kindly write out the correct way.
My code for example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Fields js/php to MySql need to submit dynamically to the database</title>
<?php
require ('database.php');
?>
<script type="text/javascript">
var counter = 1;
var collector = "";
function addfields(indx)
{
var tbl = document.getElementById('table_id');
var newtr = document.createElement('tr');
counter = counter + indx;
newtr.setAttribute('id','tr'+counter);
newtr.innerHTML = '<td><input type="checkbox" name="checkb'+counter+'" id="checkb'+counter+'" value="'+counter+'" onclick="checkme('+counter+')"></td><td><input type="text" name="text1[]"></td><td><textarea name="textarea1[]"></textarea></td>';
tbl.appendChild(newtr);
}
function checkme(dx)
{
collector += dx+",";
}
function deletetherow(indx)
{
var col = collector.split(",");
for (var i = 0; i < col.length; i++)
{
var remvelem = document.getElementById('tr'+col[i]);
var chckbx = document.getElementById("checkb"+col[i]);
if(remvelem && chckbx.checked)
{
var tbl = document.getElementById('table_id');
tbl.removeChild(remvelem);
}
}
}
</script>
</head>
<body>
<form enctype="multipart/form-data" id="1" style="background-color:#ffffff;" action="<?php echo $_SERVER['PHP_SELF']; ?>"></form>
<table id="table_id" >
<tr id="tr1" class="trmain">
<td>
</td>
<td>
<input type="text" name="text1[]">
</td>
<td>
<textarea name="textarea1[]"></textarea>
</td>
</tr>
</table>
<input type="button" value="Add" onClick="addfields(1);" />
<input type="button" value="Delete" onClick="deletetherow()" />
<input type="submit" value="Send" id="submit" name="submit"/>
<?php
if(isset($_POST['submit'])) {
for ($i=0; $i < count($_POST['text1']); $i++ )
{
$ced = stripslashes($_POST['text1'][$i]);
$erg = stripslashes($_POST['textarea1'][$i]);
$bnt = mysql_query("INSERT INTO tablename (first, second) VALUES ('$ced', '$erg')")or
die ('Error: '. mysql_error() );
}
}
?>
</body>
</html>
Here is a perma link for anyone: Dynamic Fields js/php to MySql need to submit dynamically to the database
If you are seeking answer to this subject, then Sean was right, it actually never overwrote the other as just first inputs submitted to MySQL as others ignored as wasn't part of loop. His innerhtml dynamic with loop is working.
If you want the code, its' above-edited or take from perma. There are not a whole lot of these working examples on the web, now you can go further with jQuery with this and getting more popular.

Update price shown onchange

I am simply trying to get a price shown, to update on an onchange event. Right now, this is only just showing me both values of the onchange ids I'd just like to have someone click a check box and then it updates the price that was already shown to the new value.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
</head>
<body>
<table>
<tr>
<td>
<input type="checkbox" id="extras" value="25.00" onChange="calc()">
</td>
<td>
<input type="checkbox" id="rush" value="35.00" onChange="calc()">
</td>
<td>
<input id="total" type="text" value="90.00" />
</td>
</tr>
</table>
</body>
<script type='text/javascript'>
function calc() {
var extras = document.getElementById('extras').value;
var rush = document.getElementById('rush').value;
var result = document.getElementById("total");
result.value = extras + rush;
}
</script>
</html>
You can do:
$('input[type=checkbox]').change(function () {
var val = parseFloat(this.value),
totalVal = parseFloat($('#total').val());
if (this.checked) {
$('#total').val((totalVal + val).toFixed(2));
} else {
$('#total').val((totalVal - val).toFixed(2));
}
});
Fiddle Demo
a non jquery solution could be to check for checked value. You also need to convert the value which is text to float otherwise it won't be a valid sum but just concatenation of strings.
var extrasCB = document.getElementById('extras');
var extras = 0;
if(extrasCB.checked) {
extras = parseFloat( extrasCB.value );
}

Getting rid of Value attribute of a textBox when using clone method in jQuery

I'm having a problem with this form I'm working on. Whenever I add, or refresh the page, the values are still there. I believe this is because the clone method copies the value attribute from the textBox. Is there any way I can get rid of them when I add another textBox?
<html>
<head>
<title>JQuery Example</title>
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript">
function removeTextBox()
{
var childCount = $('p').size() //keep track of paragraph childnodes
//this is because there should always be 2 p be tags the user shouldn't remove the first one
if(childCount != 2)
{
var $textBox = $('#textBox')
$textBox.detach()
}
}
function addTextBox()
{
var $textBox = $('#textBox')
var $clonedTextBox = $textBox.clone()
//document.getElementById('textBox').setAttribute('value', "")
$textBox.after($clonedTextBox)
}
</script>
</head>
<body>
<form id =
method="POST"
action="http://cs.harding.edu/gfoust/cgi-bin/show">
<p id= "textBox">
Email:
<input type = "text" name="email" />
<input type ="button" value ="X" onclick = "removeTextBox()"/>
</p>
<p>
Add another email
</p>
<input type="submit" value="submit"/>
</form>
</body>
</html>
The Following addition should work:
var $clonedTextBox = $textBox.clone();
$($clonedTextBox).val('');

Categories