jQuery event triggerred for elements with the same class - javascript

I have the following html ....
<INPUT name="debit[]" id=d1 class='Right debit' type="text" value="" /><br/>
<INPUT name="debit[]" id=d2 class='Right debit' type="text" value="" /><br/>
<INPUT name="debit[]" id=d3 class='Right debit' type="text" value="" /><br/>
<INPUT name="debit[]" id=d4 class='Right debit' type="text" value="" /><br/>
<INPUT name="debit[]" id=d5 class='Right debit' type="text" value="" /><br/>
<INPUT name="iDebit[]" id=iDebit type="text" value="" /><br/>
and
<script>
$("input.debit").keyup(function(){
var total = sumSizes('debit');
$("#iDebit").val(total);
});
function sumSizes(calc) {
var total = 0;
$('.' + calc).each(function() {
total += parseFloat($(this).val(), 10) || 0;
});
return (total);
}
function addRow(tableID){
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0;i<colCount;i++){
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
switch(newcell.childNodes[0].type){
case "text":
newcell.childNodes[0].value="";
break;
case "checkbox":
newcell.childNodes[0].checked=false;
break;
case "radio":
newcell.childNodes[0].checked=false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex=0;
break;
}
newcell.childNodes[0].id=newcell.childNodes[0].id+rowCount;
}
updateCredit();
updateBalance();
}
</script>
What I want is that whenever I change a value in any of the input
elements, javascript should calculate the 'total' and update input element with id #iDebit.
It is only working for the first INPUT element. How do I fix this to
work for any of the INPUT elements with class=debit?

Your code seems to work for me but my only advice would be to use ID tags for specific notation and maybe that will work better in your browser.

Related

Always increase field by one and edit values without button

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;
}

How To Get Total Value Of Inputs With Vanilla Javascript?

I'm trying to get the total amount from input value with pure JavaScript but It's returning blank. The format of the amount value for each input is as follow 0.00
PHP
//rest of code
$i = 0;
while ($row = mysqli_fetch_array($result)) {$i++;
<input id="Amount'.$i.'" name="Amount" value="'.$plan['price'].'" type="text">
}
echo ' <input id="total" name="finalResult" value="" type="text">';
JS
function totalResult(){
var arr = document.getElementsByName('Amount');
var total=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
total += parseInt(arr[i].value);
}
document.getElementById('total').value = total;
}
Use HTML5's query selctor API querySelectorAll() like the following:
function totalResult(){
var arr = document.querySelectorAll('input[name=Amount]');
var total=0;
arr.forEach(function(item){
if(parseInt(item.value))
total += parseInt(item.value);
});
document.getElementById('total').value = parseFloat(total).toFixed(2);
}
totalResult();
<input id="Amount1" name="Amount" value="10.00" type="text" />
<input id="Amount2" name="Amount" value="20.00" type="text" />
<input id="Amount3" name="Amount" value="30.00" type="text" /><br>
Result:
<input id="total" name="finalResult" value="" type="text">

jQuery - What is the good way to implement continouns ranking

Suppose I have 4 input fields now:
<table>
<tr><th></th><th>Factor 1</th></tr>
<tr><td>Company A</td><td><input type="text" name="text1" id="text1"></td></tr>
<tr><td>Company B</td><td><input type="text" name="text2" id="text2"></td></tr>
<tr><td>Company C</td><td><input type="text" name="text3" id="text3"></td></tr>
<tr><td>Company D</td><td><input type="text" name="text4" id="text4"></td></tr>
</table>
The inputs are integer from 1 to 4 uniquely in each input field. It is like a ranking for which Company is the best for this Factor, and which is the second and so on.
For example:
When we input 1, 3, we alert 2 is missing in the ranking.
When we input 1, 2, 4, then we alert 3 is missing.
Inputs are not required, but when there are inputs, the sequence must from 1 to 4.
Here is the code I tried.
function checkMissingRank(object){
object.change(function() {
var max = 0;
var actSum = 0;
var rows = object.length;
for(var i=1 ; i<=rows ; i++){
if($('#text'+i+'').val() != ""){
var actVal = parseInt($('#text'+i+'').val());
//alert("actVal: "+actVal);
actSum = actSum + actVal;
if(actVal>max){
max=actVal;
//alert("max: "+ max);
}
}
}
//alert("actSum: "+ actSum);
totalSum = ((1+max)*max)/2;
//alert("totalSum: "+ totalSum);
var missVal = totalSum - actSum;
//alert("missVal "+ missVal);
if(missVal != 0){
alert("Ranking "+missVal+" is missing.");
}
});
}
checkMissingRank($('input[name^="text"]'));
It is working fine when just one Value missing (1 missing from 1 ,2 ,3, 4). But when 1, 2 both missing, it return 3 is missing which is the sum of 1 and 2. Is there a better way to do this?
HTML :
<input type="text" name="text1" id="text1">
<input type="text" name="text2" id="text2">
<input type="text" name="text3" id="text3">
<input type="text" name="text4" id="text4">
<input type="button" id="btnTest">
and Jquery:
$("#btnTest").click(function() {
$('input[type=text]').each(function() {
var msg = $(this).prop("id");
if ($(this).val() == "") {
switch (msg) {
case ("text1"):
alert('miss 1');
break;
case ("text2"):
alert('miss 2');
break;
case ("text3"):
alert('miss 3');
break;
case ("text4"):
alert('miss 4');
break;
}
}
})
});
Fiddle Sample https://jsfiddle.net/shree/5ucxau2n/1/
I create a sample on button click.Hope its help.
This alerts each input that is missing.
$(function(){
$("button").on("click", function(){
$("input").each(function(){
if($(this).val() == ""){
alert($(this).attr("id") + " is missing");
}
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm" id="myForm">
<input type="text" name="text1" id="text1">
<input type="text" name="text2" id="text2">
<input type="text" name="text3" id="text3">
<input type="text" name="text4" id="text4">
</form>
<button>Enter</button>
This is if you just want a list of all the input elements that are missing. Only one alert box:
$("button").on("click", function(){
var str = ""
$("input").each(function(){
if($(this).val() == ""){
str += $(this).attr("id") + " and "
}
})
alert(str + " is missing");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form name="myForm" id="myForm">
<input type="text" name="text1" id="text1" placeholder = "type 1">
<input type="text" name="text2" id="text2" placeholder = "type 2">
<input type="text" name="text3" id="text3" placeholder = "type 3">
<input type="text" name="text4" id="text4" placeholder = "type 4">
</form>
<button>Enter</button>
Any Questions? let me know.

how to concatenate two or more text box values in one text box

I want to concatenate two or more text box values in one text box.Here I am getting values using id but that id will be dynamically added it means text box will dynamically added.For dynamically adding text box I am using for loop but am getting the value only the last text box value only becaues for loop executed.I want all text box values.Please help me to get me out.Thank you in advance.
Here is the code for dynamic text box process:
In this am using printwriter object in servlet
int nums=5;
out.println("<input type='text' id='static'>");
int i;
for (i=0;i<nums; i++) {
out.println("<input type='text' Style='width:30px' maxlength='1' id='id"+i+"'onkeyup='sum();'> ");
out.println("<script>function sum(){ alert('id"+i+"'); var txtFirstNumberValue=document.getElementById('id'+i+'').value;var result = document.getElementById('static').value + txtFirstNumberValue;alert(result);if (isNaN(result)){ document.getElementById('static').value = result; }}</script>");
}
but if I use static text box I am getting what I need but I need that in dynamic process.
here is the code for static text box process:
<input type="text" maxlength="1" id="1" onkeyup="sum();"/>
<input type="text" maxlength="1" id="2" onkeyup="sum();"/>
<input type="text" maxlength="1" id="3" onkeyup="sum();"/>
<input type="text" id="4"/>
function sum() {
var txtFirstNumberValue = document.getElementById('1').value;
var txtSecondNumberValue = document.getElementById('2').value;
var txtThirdNumberValue = document.getElementById('3').value;
var result = txtFirstNumberValue + txtSecondNumberValue + txtThirdNumberValue;
if (isNaN(result)) {
document.getElementById('4').value = result;
}
}
Please help me to find out the solution.Thank you in advance.
I would not use inline JavaScript and I would give my elements proper IDs if I really need them otherwise I would use classes.
$(document).ready(function() {
$('.in').on('input',function() {
var allvals = $('.in').map(function() {
return this.value;
}).get().join('');
$('.out').val( allvals );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="in" type="text" maxlength="1" id="i1"/>
<input class="in" type="text" maxlength="1" id="i2"/>
<input class="in" type="text" maxlength="1" id="i3"/>
<input class="out" type="text" id="i4"/>
<script type="text/javascript">
$(document).ready(function(){
var cls = document.getElementsByClassName('test');
var i =0;
var len = cls.length;
var tot = 0;
for(i=0;i<l;i++){
var cur = cls[i].value;
tot = parseInt(cur)+tot;
}
//document.getElementById("id"+cls.length).value = tot; //set the value for last element as the tot var
});
</script>
<body>
<input type="text" maxlength="1" value="1" id="1" class="test"/>
<input type="text" maxlength="1" value="2" id="2" class="test"/>
<input type="text" maxlength="1" value="3" id="3" class="test"/>
</body>
$(document).ready(function() {
$('.in').on('input',function() {
var allvals = $('.in').map(function() { return this.value; }).get().join('');
$('.out').val( allvals );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="in" type="text" maxlength="1" id="i1"/>
<input class="in" type="text" maxlength="1" id="i2"/>
<input class="in" type="text" maxlength="1" id="i3"/>
<input class="out" type="text" id="i4"/>
$(document).ready(function() {
$('.in').on('input',function() {
var allvals = $('.in').map(function() {
return this.value;
}).get().join('');
$('.out').val( allvals );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="in" type="text" id="i1"/>
<input class="in" type="text" id="i2"/>
<input class="in" type="text" id="i3"/>
<input class="out" type="text" id="i4"/>

implementing quantity to update price of product and total price

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!

Categories