get all the input value and make an addition - javascript

<ul class="liste_couleur_qty">
<li style="margin-bottom: 20px;">
<dl>
<table width="200" border="0">
<tbody><tr>
<td width="50%">
<span style="display: block; font-size: 13px; line-height: 16px; margin-bottom: 2px;margin-right: 0px;margin-left: 20px;">Noir</span>
</td>
<td width="50%"><div class="add-to-cart">
<label for="qty-2195">qty :</label>
<input type="text" class="input-text qty calcul_qty_product" title="Qté" value="0" autocomplete="off" maxlength="5" data-product_color="127" id="qty-2195" name="qty-2195" onblur="addToCartPlus(2195, 127, this);">
</div></td>
</tr>
</tbody></table>
</dl>
</li>
<li style="margin-bottom: 20px;">
<dl>
<table width="200" border="0">
<tbody><tr>
<td width="50%">
<span style="display: block; font-size: 13px; line-height: 16px; margin-bottom: 2px;margin-right: 0px;margin-left: 20px;">Blanc</span>
</td>
<td width="50%"><div class="add-to-cart">
<label for="qty-2196">qty :</label>
<input type="text" class="input-text qty calcul_qty_product" title="Qté" value="0" autocomplete="off" maxlength="5" id="qty-2196" name="qty-2196" onblur="addToCartPlus();">
</div></td>
</tr>
</tbody></table>
</dl>
</li>
<li style="margin-bottom: 20px;">
<dl>
<table width="200" border="0">
<tbody><tr>
<td width="50%">
<span style="display: block; font-size: 13px; line-height: 16px; margin-bottom: 2px;margin-right: 0px;margin-left: 20px;">Blanc</span>
</td>
<td width="50%"><div class="add-to-cart">
<label for="qty-2196">qty :</label>
<input type="text" class="input-text qty calcul_qty_product" title="Qté" value="0" autocomplete="off" maxlength="5" id="qty-2196" name="qty-2196" onblur="addToCartPlus();">
</div></td>
</tr>
</tbody></table>
</dl>
</li>
</ul>
<div id="qtyvalue"><div>
i want to do:
change the content of a div(qtyvalue) dynamically when the input value changes? if there are more input text vaule, add them together then shows the number in the div(qtyvalue). i using the following code.
input.onkeyup = function() {
var result = 0;
$('.liste_couleur_qty li input').each(function(){
result += parseInt(this.value, 10);
});
document.getElementById('qtyvalue').innerHTML = result.value;
}
but the code doesn't work, i don't know how to loop the input,if there are two or many input text box. thank you.

What you want is this:
$(document).ready(function() { //wrap in a document.ready event handler
$('input').on('keyup', function() { //bind using jQuery
var result = 0;
$('.liste_couleur_qty li input').each(function() {
result += parseInt(this.value, 10);
});
$('div#qtyvalue').text(result); //result.value doesn't exist, use result.
});
});​
Here's a demo: http://jsfiddle.net/jeRdA/
UDPATE:
To allow for users changing the value of any of the inputs to ''(e.g., blank, or empty) or a non-numeric value, modify the line:
result += parseInt(this.value, 10);
to:
result += parseFloat(this.value, 10) || 0;
Updated fiddle: http://jsfiddle.net/jeRdA/3/

Try this:
var $inputs = $('.liste_couleur_qty li input');
$inputs.keyup(function() {
var result = 0;
$inputs.each(function(){
result += parseInt(this.value, 10);
});
$('#qtyvalue').html(result);
});
This would need to be in a document ready handler or in a script block after the elements in question (many people put their scripts at the end of the body).
In your code, input.onkeyup = ... wouldn't work because there is no variable input (it doesn't automatically pick up all input elements), and also using someElement.onkeyup = only lets you attach a handler to one element at a time. Use jQuery to bind the keyup handler instead. Also, to use the total at the end just use result, using result.value wouldn't work.

Related

How to enable disabled fields using jQuery?

function disableField()
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$("input").not('.DeleteButton').prop('disabled', false);
}else{
$("input").prop('disabled', false);
}
}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').not('.DeleteButton').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField()" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
I have a table with a drop-down column in it. Whenever i change the values of drop-down my corresponding fields get enabled. The problem i am getting is if i change the values of my drop-down of previous row the columns of current row also get enabled.Any help will be appreciated. Thanks.
Edit:I have added 'Add Row' function too in my code.
I have added some changes in your disableField function. Pass parameter(this) disableField(this) in that function on chnage event.
function disableField(elem)
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$(elem).closest('tr').find("input").not('.DeleteButton').prop('disabled', false);
}
else{
$(elem).closest('tr').find("input").prop('disabled', false);
}}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField(this)" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
All in all there is to much extraneous code so the following answer has different code yet can be applied to the clunky code provided in question. I recommend that your code be more streamlined like the following demo provided in this answer.
Here's some suggestions:
If you are using multiple form controls (ex. <button>, <input>, <textarea>, <select>, etc), wrap everything into a <form>
If you have multiple tags (aka elements) that the user can click, submit, reset, change, input, etc register the events to the <form>
In order to find the exact form control that was clicked, changed, etc. use the Event.target property to find it or this keyword and the Event.data parameter.
$('form selector').on('event type', Event.data, callback function)
The #id and [name] attributes are unnecessary unless you are using certain Web APIs such as HTMLFormControlsCollection or HTMLFormElement
Never use event attributes (ex onchange="callback()") when using jQuery. Use the proper jQuery method or .on() method.
// jQuery method
$(selector).click(callback)
// .on() method
$(selector).on('click', callback)
Minor details:
The [type] attribute does not apply to the <select> tag.
Use <th> instead of <td> within <thead>
[maxlength] of 500 is ridiculous. Use <textarea> instead of <input>
Details are commented in demo
/*
Register form.io to the 'submit', 'click', and 'change' events
Note the callback function does not have `()` suffixed because it would be
interpreted as: "run function now"
The callback function doesn't run immediately it runs when a registered event is triggered.
*/
$('.io').on('submit click change', eventHandler);
// Define the counter
let counter = 0;
// Always pass the Event Object when defining a callback function
function eventHandler(event) {
// The Event Object has several properties...
// Get the type of event triggered (ie submit, change, or click)
let eType = event.type;
/*
Get the origin element of event
if 'submit' target will be <form>
if 'click' target will be <button>
if 'change' target will be <select>
*/
let eNode = event.target;
// Pass the event type through a switch() function...
switch (eType) {
// if type is 'submit'...
case 'submit':
// Create a deep clone of the first row
let clone = $('.grid tr:first-child').clone(true, true);
// Add clone as the last child of the <tbody>
$('.grid').append(clone);
// On .each() elment with class '.data' found within the clone...
clone.find('.data').each(function(i) {
// disable it
this.disabled = true;
// remove its value
this.value = '';
});
// Increment the counter by 1
counter++;
// Dereference the clone and assign id as row+counter
clone[0].id = `row${counter}`;
/*
Prevent default behavior:
Reset <form>
Send data to a server
*/
event.preventDefault();
// Stop event from bubbling any further up the event chain
event.stopPropagation();
// ...otherwise skip this case and continue onto the next case
break;
// if type is 'click'...
case 'click':
// if the clicked element (ie <button>) has class: '.del'...
if ($(eNode).hasClass('del')) {
// Get the clicked <button>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if that <tr> is NOT the first <tr>...
if (row.index() !== 0) {
// remove the <tr>
row.remove();
}
}
event.stopPropagation();
break;
// if type is 'change'...
case 'change':
// if changed element (ie <select>) class is '.type'...
if ($(eNode).hasClass('type')) {
// Get the changed <select>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if changed <select>'s value is NOT "X" return true otherwise return false
let pick = eNode.value !== "X" ? true : false;
/*
On .each() element with class .data within the <tr>
disable the .data if <select>'s value is "X"
Otherwise enable the .data
and then remove the .data value
*/
row.find('.data').each(function(i) {
this.disabled = !pick;
this.value = '';
});
}
event.stopPropagation();
break;
default:
event.stopPropagation();
break;
}
}
:root {
font: 400 3vw/1.2 Arial
}
form {
width: max-content;
margin: 10px auto
}
table {
table-layout: fixed;
border-collapse: separate;
border-spacing: 4px;
width: 90vw
}
th:first-of-type {
width: 20%
}
th:nth-of-type(2) {
width: 35%
}
th:nth-of-type(3) {
width: 35%
}
th:last-of-type {
width: 10%
}
td {
padding: 0 8px
}
select,
textarea,
button {
display: block;
min-width: 97%;
min-height: 1.2rem;
font-size: initial;
}
select {
padding: 2px 0 2px 2px
}
textarea {
resize: vertical;
overflow-y: auto;
overflow-x: hidden
}
<form class='io'>
<table>
<thead>
<tr>
<th>Type</th>
<th>Desciption</th>
<th>Image/URL</th>
<th><button>➕</button></th>
</tr>
</thead>
<tbody class='grid'>
<tr>
<td>
<select class='type'>
<option value="X" default></option>
<option value="GDS">Guides</option>
<option value="PRO">Promos</option>
<option value="TEM">Templates</option>
<option value="VID">Videos</option>
</select>
</td>
<td><textarea class='desc data' rows='1' cols='20' disabled></textarea></td>
<td><textarea class='urls data' rows='1' cols='20' disabled></textarea></td>
<td><button class='del' type='button'>❌</button></td>
</tr>
</tbody>
</table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to fix sum of multiple input fields if same class in one <td contenteditable> not <td><input>

I can't sum on table td "jumlah" for "total"
<script>
$(document).on("change", ".jumlah", function() {
var sum = 0;
$(".jumlah").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
</script>
<input type="text" id="total" class="total" value="" />
I expect the output for total from jumlah
Elements with the [contenteditable] attribute will not have a [value] attribute because:
Only non-interactive, non-void, flow and phrase elements like <div></div>, <section></section>, <spab></span> etc. can have [contenteditable].
Only form controls such as <input>, <textarea>, <output>, etc. can have the [value] attribute.
So instead of .val() use .text() since text is the content between the tags of non-form controls. The important change is a ternary:
if this is an input get its value otherwise get its text
sum += $(this).is('input') ? +$(this).val() : +$(this).text();
The minor changes are:
input event instead of change because it looks slick.
The form is registered to the input event instead of document.
$('.totals').on("input", ".subtotal", function() {
let sum = 0;
$(".subtotal").each(function(){
sum += $(this).is('input') ? +$(this).val() : +$(this).text();
});
$(".total").val(sum);
});
:root {font:700 16px/1.2 Consolas}
input, output, data {display:inline-block;font:inherit;text-align:right;width:125px;}
output, data {width:50px}
data {outline:1px solid #aaa;padding:2px 17px 2px 0px;margin:1px 0px 1px 2px;width:110px}
<form class='totals'>
<table>
<tr><td><input class="subtotal" type='number' value='0'></td></tr>
<tr><td><input class="subtotal" type='number' value='0'></td></tr>
<tr><td><input class="subtotal" type='number' value='0'></td></tr>
<tr><td><data class="subtotal" contenteditable>0</data></td></tr>
<tr><td><data class="subtotal" contenteditable>0</data></td></tr>
<tr><td><data class="subtotal" contenteditable>0</data></td></tr>
<tr><td>Total: <output class="total">0</output></td></tr>
</table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have created a very simple example with what you need, I think you can easily implement something similar in your code.
$('.jumlah').on('input', function() {
let elementsToSum = $(document).find('.jumlah');
let sum = 0;
for (let ele of elementsToSum) {
// Parse the value of the <td> to integer
let eleIntValue = parseInt($(ele).html());
if (!isNaN(eleIntValue)) {
// Only add it to the sum if it is a number (not empty)
sum += eleIntValue;
}
}
// Change the value of <input> with the new calculated sum
$('#total').val(sum);
});
td {
width: 50px;
}
<table border="1">
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
</table>
<br>
<input type="text" id="total" class="total" value="" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

copy a table row of design HTML

I want the moment you click on "create row", line 2 is duplicated with the formatting rule: input, select ..
In addition to the first column I want each time to exceed a count of +1 in "count number".
Once I click on Delete Row - it will let me delete the last line except line 1!
Thanks for the helpers!
this is the code:
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable" class="table table-bordered table-hover" style="font-size: 12px; font-family: Arial;">
<thead>
<tr>
<th style="text-align: right;">השתתפות / שוברים</th>
<th style="text-align: right;">סכ"ה ימים</th>
<th style="text-align: right;">עד תאריך</th>
<th style="text-align: right;">מתאריך</th>
<th style="text-align: right;">שם משפחה</th>
<th style="text-align: right;">שם פרטי</th>
<th style="text-align: right;">מ.א</th>
<th style="text-align: right;">number count</th>
</tr>
</thead>
<tbody>
<tr class="warning">
<td style="text-align: center;">
<select style="font: 12px 'Fira Sans', sans-serif;width: 94px;margin: 0.4rem;text-align-last: right;">
<option value="volvo">השתתפות</option>
<option value="saab">שוברים</option>
</select>
</td>
<td style="text-align: right;"><input type="number" id="fname2" name="firstname" style="font: 12px 'Fira Sans', sans-serif;width: 31px;margin: 0.4rem;text-align-last: center;"></td>
<td style="text-align: right;">
<fieldset>
<div>
<input type="date" name="trip" style="font: 12px 'Fira Sans', sans-serif;width: 113px;margin: 0.4rem;">
</div>
</fieldset>
</td>
<td style="text-align: right;">
<fieldset>
<div>
<input type="date" name="trip" style="font: 12px 'Fira Sans', sans-serif;width: 113px;margin: 0.4rem;">
</div>
</fieldset>
</td><td style="text-align: right;">
<input type="text" id="fname2" name="firstname" style="font: 12px 'Fira Sans', sans-serif;width: 55px;margin: 0.4rem;text-align: right;">
</td>
<td style="text-align: right;">
<input type="text" id="fname2" name="firstname" style="font: 12px 'Fira Sans', sans-serif;width: 52px;margin: 0.4rem;text-align: right;">
</td><td id=check style="text-align: right;">
<input type="number" name="firstname" style="font: 12px 'Fira Sans', sans-serif;width: 64px;margin: 0.4rem;text-align-last: center;">
</td>
<td style="text-align: center;padding-top: 20px;">1
</td>
</tr>
</tbody>
</table>
<br><br>
<p id="demo" onclick="myCreateFunction()">Create row</p> <br>
<p id="demo" onclick="myDeleteFunction()">Delete row</p>
<script>
function myCreateFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(0);
var cell3 = row.insertCell(0);
var cell4 = row.insertCell(0);
var cell5 = row.insertCell(0);
var cell6 = row.insertCell(0);
var cell7 = row.insertCell(0);
var cell8 = row.insertCell(0);
cell1.innerHTML = 1;
cell2.innerHTML = 2;
cell3.innerHTML = 3;
cell4.innerHTML = 4;
cell5.innerHTML = 5;
cell6.innerHTML = 6;
cell7.innerHTML = 7;
cell8.innerHTML = 8;
}
function myDeleteFunction() {
document.getElementById("myTable").deleteRow(-1);
}
</script>
</body>
</html>
functions down
A fast and easy solution (though maybe not best for long term use) is to have a global variable called something like "depth", start it at let depth = 0 then every time you add a line depth++;, if you remove a line only let it remove the line if(depth >= 0) then you will never be deleting the starting line that already exists.
Another way to do it, and maybe more scalable if this is for a bigger project, is to keep track of the number of lines in an array, each time you add a line, you arr.push(line); when you remove a line you arr.splice(indexofline,1); This gives you the ability to not just track what line you're at, but you could also push information about the line that you could use in later code for expanding the program.
You have some problems in your code.
First of all HTML IDs have to be unique. You are using multiple identical IDs.
Some input fields have the same name. This does not have to be a problem by all means, however, many server-side script languages (e.g. PHP) just overwrite multiple usages and expose just the last one. PHP forms arrays if you use names like <input name="firstname[]">.
A non-empty <title>My Title</title> tag is mandatory in HTML5.
Further more
Documents should declare the charset they are encoded with.
It is always a good idea to have an <html> tag with a lang attribute.
Avoid inline styles. Use stylesheets instead.
Inline event handlers like onclick are old-school. Apply event listeners instead.
There are semantical senseless <div> elements in the cells.
<fieldset> elements containing only one field do not make semantical sense, especially when they devide two related dates. A fieldset enclosing both dates within the same cell could make sense. Use css outline or similar to get the visual effect if you need it.
To get a copy of another row, you can use the cloneNode method.
The number of rows can be determined with table.rows.length. You can use it to fill the 'number count' cell.
If you do need IDs for some reason, they have to be unique per document. This means, you need different IDs even in each row. When copying, you have to change the id in some way - e.g. append the row number.
I have added some demo <label> just to illustrate how to change necessary IDs and the label's for Attribute which is connected to the ID of the according form field. Of course a label in a column with a caption does not really make sense - it's only for teaching purposes.
Copying the first row might be a bad choice, since the entered values are copied as well. More common would be to copy the last entered row. However, there is another alternative. You can use a clean template. <template> elements are not rendered by the browser and thus they are not part of the DOM. You get DOM-like access via the content property.
document.addEventListener('DOMContentLoaded', evt =>
{
const
minRowsPreserved = 2,
byId = document.getElementById.bind(document)
;
function myCreateFunction()
{
let
table = byId("myTable"),
rowCount = table.rows.length,
row = byId('tpl-row').content.firstElementChild.cloneNode(true)
;
// In case you need IDs: Append the row number seperated by '-' to each ID since IDs must be unique.
row.querySelectorAll('[id]').forEach(e => e.id += '-' + rowCount);
// Similar for clickable labels depending on IDs, however, there is no shortcut for the `for` attribute.
row.querySelectorAll('label[for]').forEach(e => e.setAttribute('for', e.getAttribute('for') + '-' + rowCount));
// Content of the last cell becomes the row number.
row.cells[row.cells.length-1].textContent = rowCount;
// now we append the row to the table body after id-conflicts should be resolved
table.tBodies[0].appendChild(row);
}
function myDeleteFunction() {
let table = byId("myTable");
if(minRowsPreserved < table.rows.length)
table.deleteRow(-1);
}
byId('btn-create').addEventListener('click', myCreateFunction);
byId('btn-delete').addEventListener('click', myDeleteFunction);
// add a first row on start
myCreateFunction();
})
#myTable
{
font-size : 12px;
font-family : Arial;
border : 1px solid black;
text-align : center;
margin-bottom: 2em;
}
#myTable td
{
border : 1px solid black;
padding: 0.4rem;
}
#myTable th
{
text-align: right;
}
#myTable input,
#myTable select
{
font : 12px 'Fira Sans', sans-serif;
}
#myTable input[type="text"] { text-align : right; }
#myTable input[type="number"] { text-align-last: center; }
#myTable select { text-align-last: right; }
#myTable input[type="date"] { width : 113px; }
.num1 input { width : 31px; }
.first-name input { width : 55px; }
.last-name input { width : 52px; }
<!DOCTYPE html>
<html lang="he">
<head>
<meta charset="UTF-8">
<title>dynamic table form</title>
<body>
<form method="post">
<table id="myTable" class="table table-bordered table-hover">
<thead>
<tr>
<th>השתתפות / שוברים</th>
<th>סכ"ה ימים</th>
<th>עד תאריך</th>
<th>מתאריך</th>
<th>שם משפחה</th>
<th>שם פרטי</th>
<th>מ.א</th>
<th>number count</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<button id="btn-create">Create row</button>
<button id="btn-delete">Delete row</button>
<template id="tpl-row">
<tr class="warning">
<td class="car">
<select id="car" name="car[]" style="width: 94px; text-align-last: right;">
<option value="volvo">השתתפות</option>
<option value="saab">שוברים</option>
</select>
</td>
<td class="num1" > <input type="number" id="num1" name="num1[]" > </td>
<td class="trip-start"> <input type="date" id="trip-start" name="tripstart[]" > </td>
<td class="trip-end" > <input type="date" id="trip-end" name="tripend[]" > </td>
<td class="first-name"> <input type="text" id="first-name" name="firstname[]" > </td>
<td class="last-name" > <input type="text" id="last-name" name="lastname[]" > </td>
<td class="check">
<label for="num2">demo label:</label>
<input type="number" id="num2" name="num2[]" style="width: 64px; text-align-last: center;">
</td>
<td></td>
</tr>
</template>

how to wrap string containing dynamically loaded value

I can't see errors in my logic maybe You'll help Me
I've got this at the moment
$(document).ready(function() {
var str = $('#formElements').text();
str = str.slice(104,112);
alert(str);
$('#formElements:contains('+ str +')').load(function(){
$(this).html().replace(str, '<div class="price-cal-check">'+str+' <span id="priceout"></span>zł</div>');
});
});
form {
display: block;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<form method="post" name="form" action="javascript:void(0);">
<div id="formElements" style="float:right; min-height: 280px; margin-left: 20px; width: 575px;">
<table>
<tbody>
<tr>
<td>Quantity:</td>
<td>Paper type:</td>
</tr>
<tr>
<td><input name="amount" value="1" type="text"></td>
<td> <select name="paper">
<option value="1">250 gsm</option>
</select>
</td>
</tr>
</tbody>
</table>
Price: $
<br>
<input class="submitToCart" name="addCart" value="Add to cart" role="button" aria-disabled="false" style="margin-top: 4px;" type="submit">
</div>
</form>
the value of <span id="priceout">27,00</span> is generated dynamicaly after page loads with jQuery.
so he output of str looks like this Price: $
all i want to do is to put whole string Price: <span id="priceout">27,00</span>$ in to div. but my code isn't work
what I'm doing wrong ?
If it was up to me, I'd rather wrap that Price: in a div, give it an ID and then append it with the value like:
<div id="price"> Price: </div>
and in your function
$('#price').append('<span id="priceout">27,00</span>$');
Hope it helps.
Ok I've found a solution now js looks like this
$('#formElements').each(function() {
var form = $(this);
var str = form.html();
var str1 = str.slice(225,260);
//alert(str);
form.html(str.replace(str1,'<div class="price-cal-check">'+ str1 +'</div>'));
});
and it works

Use javascript to get total of hours from start to stop

So I've been searching this site for weeks trying to find a solution to this and have looked at EVERY question asked about getting the sum of input fields or finding the value of start and stop times but none of them solve my issue.
The included snippet shows a time sheet that I currently am able to input the reg (regular) and ot (overtime) hours and the sum of each row is populated in the total box but at the bottom I have to manually total the column values.
What I would like to do is eliminate the amount of data that has to be input into the form by having javascript calculate the start time and stop time and add the values to the reg, ot and total fields then sum up those columns at the bottom for the grandtotals.
The reason I want to do it like this is that this form is converted into a phone app and the less that is needed to input the fewer mistakes made.
I'm pretty new to this so I'm sure what I have is either incorrect (although it works), or there is a better way to accomplish it with less coding.
Any direction, input or help is greatly appreciated.
function sum() {
var txtFirstNumberValue = document.getElementById('reghours').value;
var txtSecondNumberValue = document.getElementById('othours').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('totalhours').value = result;
}
}
function sum2() {
var txtFirstNumberValue = document.getElementById('reghours2').value;
var txtSecondNumberValue = document.getElementById('othours2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('totalhours2').value = result;
}
}
function sum3() {
var txtFirstNumberValue = document.getElementById('reghours3').value;
var txtSecondNumberValue = document.getElementById('othours3').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('totalhours3').value = result;
}
}
function sum4() {
var txtFirstNumberValue = document.getElementById('reghours4').value;
var txtSecondNumberValue = document.getElementById('othours4').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('totalhours4').value = result;
}
}
function sum5() {
var txtFirstNumberValue = document.getElementById('reghours5').value;
var txtSecondNumberValue = document.getElementById('othours5').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('totalhours5').value = result;
}
}
</script>
<script>
$(function() {
$('#BasicExample').timepicker();
});
$(function() {
$('#BasicExample2').timepicker();
});
$(function() {
$('#BasicExample3').timepicker();
});
$(function() {
$('#BasicExample4').timepicker();
});
$(function() {
$('#BasicExample5').timepicker();
});
$(function() {
$('#BasicExample6').timepicker();
});
$(function() {
$('#BasicExample7').timepicker();
});
$(function() {
$('#BasicExample8').timepicker();
});
$(function() {
$('#BasicExample9').timepicker();
});
$(function() {
$('#BasicExample10').timepicker();
});
.ui-timepicker-wrapper {
overflow-y: auto;
height: 150px;
width: 6.5em;
background: #fff;
border: 1px solid #ddd;
-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);
-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);
box-shadow:0 5px 10px rgba(0,0,0,0.2);
outline: none;
z-index: 10001;
margin: 0;
}
.ui-timepicker-wrapper.ui-timepicker-with-duration {
width: 13em;
}
.ui-timepicker-wrapper.ui-timepicker-with-duration.ui-timepicker-step-30,
.ui-timepicker-wrapper.ui-timepicker-with-duration.ui-timepicker-step-60 {
width: 11em;
}
.ui-timepicker-list {
margin: 0;
padding: 0;
list-style: none;
}
.ui-timepicker-duration {
margin-left: 5px; color: #888;
}
.ui-timepicker-list:hover .ui-timepicker-duration {
color: #888;
}
.ui-timepicker-list li {
padding: 3px 0 3px 5px;
cursor: pointer;
white-space: nowrap;
color: #000;
list-style: none;
margin: 0;
}
.ui-timepicker-list:hover .ui-timepicker-selected {
background: #fff; color: #000;
}
li.ui-timepicker-selected,
.ui-timepicker-list li:hover,
.ui-timepicker-list .ui-timepicker-selected:hover {
background: #1980EC; color: #fff;
}
li.ui-timepicker-selected .ui-timepicker-duration,
.ui-timepicker-list li:hover .ui-timepicker-duration {
color: #ccc;
}
.ui-timepicker-list li.ui-timepicker-disabled,
.ui-timepicker-list li.ui-timepicker-disabled:hover,
.ui-timepicker-list li.ui-timepicker-selected.ui-timepicker-disabled {
color: #888;
cursor: default;
}
.ui-timepicker-list li.ui-timepicker-disabled:hover,
.ui-timepicker-list li.ui-timepicker-selected.ui-timepicker-disabled {
background: #f2f2f2;
}
.auto-style1 {
text-align: right;
}
body {
font-family: sans-serif;
}
#summation {
font-size: 16px;
font-weight: bold;
color:#174C68;
}
.txt {
background-color: #FEFFB0;
font-weight: bold;
text-align: center;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://jemtech.us/scripts/jquery.timepicker.min.js"></script>
<script src="http://jemtech.us/scripts/jquery.timepicker.js"></script>
<body>
<form action="process_form.php" method="post">
<table align="center" style="width: 498px">
<td class="auto-style1"> </td>
<td class="auto-style1"> </td>
<td class="auto-style1" style="width: 127px"> </td>
</table>
<table align="center" class="auto-style6" style="width: 857px">
<th class="auto-style5" style="width: 47px">Start</th>
<th class="auto-style5" style="width: 47px">Stop</th>
<th class="auto-style5" style="width: 43px">Reg</th>
<th class="auto-style5" style="width: 45px">OT</th>
<th class="auto-style5" style="width: 51px">Total</th>
<th class="auto-style5"></th>
<tr>
<td style="height: 26px; width: 47px;">
<input id="BasicExample" type="text" class="time" style="width: 85px" />
</td>
<td style="height: 26px; width: 47px;">
<input id="BasicExample2" type="text" class="time" style="width: 85px" />
</td>
<td style="height: 26px; width: 43px;">
<input type="text" class="txt" name="RegularHours" id="reghours" onkeyup="sum()" style="width: 45px" />
</td>
<td style="height: 26px; width: 45px;">
<input type="text" class="txt" name="OTHours" id="othours" value="0" onkeyup="sum()" style="width: 45px" />
</td>
<td style="height: 26px; width: 51px;">
<input type="text" class="txt" name="TotalHours" id="totalhours" style="width: 50px" readonly/>
</td>
<td style="height: 26px">
</td>
</tr>
<tr>
<td style="height: 26px; width: 47px;">
<input id="BasicExample3" type="text" class="time" style="width: 85px" />
</td>
<td style="height: 26px; width: 47px;">
<input id="BasicExample4" type="text" class="time" style="width: 85px" />
</td>
<td style="height: 26px; width: 43px;">
<input type="text" class="txt" name="RegularHours2" id="reghours2" onkeyup="sum2()" style="width: 45px" />
</td>
<td style="height: 26px; width: 45px;">
<input type="text" class="txt" name="OTTotal2" id="othours2" value="0" onkeyup="sum2()" style="width: 45px" />
</td>
<td style="height: 26px; width: 51px;">
<input type="text" class="txt" name="TotalHours2" id="totalhours2" style="width: 50px" readonly/>
</td>
<td style="height: 26px">
</td>
</tr>
<tr>
<td style="height: 26px; width: 47px;">
<input id="BasicExample5" type="text" class="time" style="width: 85px" />
</td>
<td style="height: 26px; width: 47px;">
<input id="BasicExample6" type="text" class="time" style="width: 85px" />
</td>
<td style="height: 17px; width: 43px;">
<input type="text" class="txt" class="txt" name="RegularHours3" id="reghours3" onkeyup="sum3()" style="width: 45px" />
</td>
<td style="height: 17px; width: 45px;">
<input type="text" class="txt" class="txt" name="OTHours3" id="othours3" value="0" onkeyup="sum3()" style="width: 45px" />
</td>
<td style="height: 17px; width: 51px;">
<input type="text" class="txt" class="txt" name="TotalHours3" id="totalhours3" style="width: 50px" readonly/>
</td>
<td style="height: 17px">
</td>
</tr>
<tr>
<td style="height: 26px; width: 47px;">
<input id="BasicExample7" type="text" class="time" style="width: 85px" />
</td>
<td style="height: 26px; width: 47px;">
<input id="BasicExample8" type="text" class="time" style="width: 85px" />
</td>
<td style="width: 43px">
<input type="text" class="txt" name="RegularHours4" id="reghours4" onkeyup="sum4()" style="width: 45px" />
</td>
<td style="width: 45px">
<input type="text" class="txt" name="OTHours4" id="othours4" value="0" onkeyup="sum4()" style="width: 45px" />
</td>
<td style="width: 51px">
<input type="text" class="txt" name="TotalHours4" id="totalhours4" style="width: 50px" readonly/>
</td>
<td>
</td>
</tr>
<tr>
<td style="height: 26px; width: 47px;">
<input id="BasicExample9" type="text" class="time" style="width: 85px" />
</td>
<td style="height: 26px; width: 47px;">
<input id="BasicExample10" type="text" class="time" style="width: 85px" />
</td>
<td style="width: 43px">
<input type="text" class="txt" name="RegularHours5" id="reghours5" onkeyup="sum5()" style="width: 45px" />
</td>
<td style="width: 45px">
<input type="text" class="txt" name="OTHours5" id="othours5" value="0" onkeyup="sum5()" style="width: 45px" />
</td>
<td style="width: 51px">
<input type="text" class="txt" name="TotalHours5" id="totalhours5" style="width: 50px" readonly/>
</td>
<td>
</td>
</tr>
</table>
<div class="auto-style1" style="width: 640px; height: 26px">
<td><strong>Total Hours</strong>
</td>
<td>
<input type="text" class="txt" name="RegTotal" id="total" style="width: 45px" readonly />
</td>
<td>
<input type="text" class="txt" name="OTTotal" id="total" style="width: 45px" readonly/>
</td>
<td style="width: 45px">
<tr id="summation">
<td style="width: 50px">
<input type="text" class="txt" name="GrandTotal" id="grandtotal" style="width: 50px" readonly/>
</td>
<td style="height: 23px"></td>
</tr>
</td>
</div>
<div style="height: 35px"></div>
<hr />
<br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
Please consider using a jQuery TimePicker Plugin as mentioned in https://www.sitepoint.com/10-jquery-time-picker-plugins/ together with https://momentjs.com/ for calculations.
As others have mentioned a date picker will make this easier for both you and your users. Either way, you will need to parse your inputs to get date objects
// With date picker
var startDate = new Date(startPicker.value);
or
// With current select inputs
// Get AM/PM hours - hourSelect should be the select element for hours
var startHrs = periodSelect.value === 'PM'
? parseInt(hourSelect.options[hourSelect.selectedIndex].value, 10)
: parseInt(hourSelect.options[hourSelect.selectedIndex].value, 10) + 12;
// No date provided so use dummy date (1970-1-1)
var startDate = new Date(
1970,
1,
1,
startHrs,
minuteSelect.options[minuteSelect.selectedIndex].value; // minuteSelect should be the select element for minutes
);
Then calculate the difference between your start and end dates. As mentioned you can use moment.js for this but the regular date object should be sufficient.
function getDifference(startDate, endDate) {
return new Date(endDate.getTime() - startDate.getTime());
}
Now you can use difference.getUTCHours() and difference.getUTCMinutes to get the total time worked. It should be trivial to get regular and overtime from the total. Remember to check that the start time is before the end.
... or there is a better way to accomplish it with less coding.
The essence of the question seems to be about how to keep the code DRY, not about whether or not to use a date-picker (though that is also an important decision).
The golden rules in spreadsheet-like apps like this with repeated rows are :
use classes for elements in the repeated rows
use ids only for non-repeating element
Here's a general framework :
jQuery(function($) {
var overtimeAfter = 8.0; // hours per day
// *** utility Constructor ***
function Hours(std, ot) {
return {'std':std, 'ot':ot};
}
Hours.prototype.add = function(otherHours) {
return new Hours(this.std+otherHours.std, this.ot+otherHours.ot);
}
// *** utility functions ***
function getTime(input) {
// Here, do whatever is necessary to convert input values to some standard abstraction:
// for example, 24H string or js Date() object.
return Number(input.val()); // simplest case
}
function timeDiffernce(t1, t2) {
// Here do whatever is necessary to calculate the time difference
// between t2 and t1, in whatever abstraction was returned by getTime().
// For example:
var t = t2 - t1; // simplest case
return (t < 0) ? 24 + t : t; // allow for t1...t2 to span midnight
}
// *** core functions ***
function calcDayHours(tr) {
// here is where you benefit from classes within the table row
var time1 = getTime($('.time1', tr));
var time2 = getTime($('.time2', tr));
var hours = timeDiffernce(time1, time2);
var std = Math.min(hours, overtimeAfter);
var ot = Math.max(0, hours - overtimeAfter);
var total = std + ot;
$('.reghours', tr).val(std);
$('.othours', tr).val(ot);
$(".totalhours", tr).val(total);
return new Hours(std, ot);
}
function calcWeekHours(hours) {
var weekHours = hours.reduce(function(week, day) {
return week.add(day);
}, new Hours(0, 0));
// these elements are unique, therefore identified by id.
$("#regTotal").val(weekHours.std);
$("#otTotal").val(weekHours.ot);
$("#grandTotal").val(weekHours.std + weekHours.ot);
return weekHours;
}
// *** master function ***
function sum() {
// Assume a table or tbody with id="timesheet"
var dayHours = $("#timesheet tr").get().map(calcDayHours);
var weekHours = calcWeekHours(dayHours);
// if you want wage calculations, then pass `weekHours` to a `calcWages()` function.
// var wages = calcWages(weekHours);
}
// Then attach `sum` as the handler for all kinds of keyup/tap/click/focus/blur events.
});
As I say, that's just a framework. There are still decisions to make, eg :
what you write in getTime() will depend on the expected date/time input format (text vs date-picker ...)
what you write in timeDiffernce() will depend on what you decide to return from getTime() (Number vs Date ...).
which ui event(s) should trigger sum().
how to specify the overtime threshold overtimeAfter - hardcoding as above will get you started.
how to accommodate overtime thresholds on a "per day", "per week" or "per month" basis - wage systems vary.

Categories