extract the value AutoNumeric.getAutoNumericElement() - javascript

I'm having trouble figuring out how to extract the value I need from the input via the name attribute. This is my html code below
`
<tr class="" id="">
<td style="vertical-align: middle; padding: .25rem;" class="isCoin">
<input hidden="" name="DisposableBagAmountList[0].DenominationStructure.DenominationStructureItems[5].IsCoin" wfd-invisible="true">
</td>
<td class="text-right w-50" style="vertical-align: middle; padding: .25rem;">
<input hidden="" name="DisposableBagAmountList[0].DenominationStructure.DenominationStructureItems[5].Id" value="1" wfd-invisible="true">
<input class="denominationStructureNumber" id="DenominationStructureItems[5].FaceValue" hidden="" name="DisposableBagAmountList[0].DenominationStructure.DenominationStructureItems[5].FaceValue" value="10.0000" readonly="" wfd-invisible="true">
<div class="faceValue">
10 </div>
</td>
<td style="vertical-align: middle; padding: .25rem;">x</td>
<td style="vertical-align: middle; padding: .25rem;">
<input class="denominationStructureNumber text-right form-control" style="min-width:80px" name="DisposableBagAmountList[0].DenominationStructure.DenominationStructureItems[5].Count" value="0" onchange="changeTotalDenominationItemsAmount()">
</td>
</tr>
And I will have in this name="DisposableBagAmountList[n].DenominationStructure.DenominationStructureItems[m].FaceValue" values like DisposableBagAmountList[0], then [1] .. [n] The same this is with DenominationStructureItems[0], then [1] .. [5]
This is my function then need to calculate all FaceValue with Numbers and give me total, for two or more diffrent denominationStructures.
function {
var total = 0;
debugger;
const numbers = $(document).find('input\[name$=".Count"\]');
//const faceValueNumbers = $(document).find('input\[name$=".FaceValue"\]');
for (let i = 0; i < numbers.length; i++) {
//old one DenominationStructure[5].CurrencyDenominationFaceValue
//DisposableBagAmountList[0].DenominationStructure.DenominationStructureItems[5].FaceValue
var faceValueNumbers = $(document).find('input[name$=".DenominationStructureItems[' + i + '].FaceValue"]');
//DenominationStructureItems[0].FaceValue.denominationStructureNumber
for (var j = 0; j < faceValueNumbers.length; j++) {
//var faceValue = $(document).find('input[id="DenominationStructure[' + i + '].FaceValue"]')[j];
var faceValue = $(document).find('input[id="DenominationStructure[' + i + '].FaceValue"]');
// $(document).find('input[id="DenominationStructure[' + i + '].FaceValue"]')[j];
var anFaceValue = AutoNumeric.getAutoNumericElement(faceValue);
var anElement = AutoNumeric.getAutoNumericElement(numbers[i]);
total += anFaceValue.getNumber() * anElement.getNumber();
}
}
var anTotal = AutoNumeric.getAutoNumericElement('#totalDenominationAmount');
if (anTotal) anTotal.set(total);
}
Basically, anFaceValue is always null for me, so I don't know how to extract the value from the input.
Does someone knows where I am wrong?
Thank you.
I am trying to extract the value for that facevalue via attr name

Have you tried getting the faceValue from DenominationStructureItems and not DenominationStructure?
Is the loop iterating? Maybe add some alerting or logs to figure it out.

Related

how to pass span value into laravel controller

I am developing some ticket selling program, where I made an auto calculating ticket price. I put the total price into a <span> tag. I'm trying to put it on <input> tag so it will be easier to pass the value into controller, but it doesn't work. I've already searching for the solution but it never comes to end. This is what my blade looks like:
<table class="text-center table-bordered" style="width:100%;">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr class="quantz">
<td class="product-quantity">
<input type="hidden" name="price[]" class="price" id="price" size="5px" readonly value="25000">
<input type="number" onchange="update();return false;" name="qty" value="1" min="1" id="quant" class="fl qty-text" >
</td>
<td class="product-total">
<span id="demo">IDR 25.000,-</span>
</td>
</tr>
<tr>
<td><h3><small>Your Cart Total - </small></h3></td>
<td><h3><input type="hidden" name="totalz" value=""><span id="sub_total">IDR 25.000,-</span></h3></td>
</tr>
</tbody>
</table>
and this is what i wrote in my jquery to get the value:
<script>
function update() {
var total = 0;
var fees = 0;
var total_fees = 0;
var tax_fix = 0;
var with_fee = 0;
var discount_amt = 0;
var no_fee= 0;
var tax= 0;
$("#form-ui tr.quantz").each(function(i,o){
if($(o).find("#quant").val()>=0){
total += $(o).find("#quant").val() * $(o).find(".price").val();
$(o).find("#demo").html(rupiah($(o).find("#quant").val() * $(o).find(".price").val()));
}
});
console.log()
fees = (total*1);
total_fees = total+fees ;
no_fee = total;
with_fee = total + total_fees;
//sub total
$("#st").val(total);
$("#sub_total").html(rupiah(total));
//convinence_fee
if(total == 0){
fees = 0;
total_fees = 0;
}
$("#fee").val(fees);
$("#conv").html(rupiah(fees));
//total_paid
$("#total_price").val(total_fees);
$("#total_paid").html(rupiah(total_fees));
$("#hide_price").val(total_fees);
}
$("#form_payment tr.quantity").change(update);
function rupiah(value){
value += '';
x = value.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return 'IDR ' + x1 + x2 + ",-";
};
</script>
is there any solution regarding this problem? should I put something in my script or my controller?
Possible with JQuery, jQuery supports chaining objects return.
In HTML :
<span id="demo">IDR 25.000,-</span>
<input id="totalz" type="hidden" name="totalz" value="">
In JS :
var data = $('#demo').html();
$('#total').val(data);
Make sure that, you have single id demo, total, if you have multiple id with same attribute, then it will conflict with JavaScript

Show calculated arithmetic mean in <td> when the button is clicked

please help me finish this, I'm getting nowhere.
what needs to be done
final results
I've explained in the pictures whats the finish goal.
This is a grade calculator.
There are 3 types of grades.. it should calculate the arithmetic mean for every category and arithmetic mean for all grades no matter which category they are.
Calculated values should be shown on the appropriate block, as shown in the picture.
input[type="number"]{
color : transparent;
text-shadow : 0 0 0 #000;
}
input[type="number"]:focus{
outline : none;
}
</style>
<body>
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Add grade</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick=""> Calculate </button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Written test</td>
<td style="width:70px; text-align: center;">Essay</td>
<td style="width:70px; text-align: center;">Class Activity</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all Writtentest, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all Essay, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all ClassActivity, inside td-->
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Arithmetic mean of all grades</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all numbers-->
</tr>
</tbody>
</table>
</div>
</body>
<script>
var ocena = 0;
var stranica = document.querySelector("#stranica")
function removeElement(obrisi) {
var dugme = obrisi.target;
stranica.removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max",5);
input.setAttribute("min",1);
var myParent = document.body;
//Create array of options to be added
var array = ["Written test","Essay","Class Activity"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
stranica.appendChild(item)
}
</script>```
var ocena = 0;
function removeElement(obrisi) {
var dugme = obrisi.target;
document.getElementById("stranica").removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max", 5);
input.setAttribute("min", 1);
var myParent = document.body;
//Create array of options to be added
var array = ["Kontrolni", "Vezbe", "Aktivnost"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
document.getElementById("stranica").appendChild(item)
}
function calcMean() {
var nameList=document.querySelectorAll('#stranica .item #mySelect');
var inputList=document.querySelectorAll('#stranica .item input');
var kontrolniList = [];
var vezbeList = [];
var aktivnostList = [];
var ocenaList = [];
for(var i=0; i< nameList.length; i++){
ocenaList.push(parseInt(inputList[i].value));
if(nameList[i].value=='Kontrolni') {
kontrolniList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Vezbe') {
vezbeList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Aktivnost') {
aktivnostList.push(parseInt(inputList[i].value));
}
}
document.getElementById("kontrolni").innerHTML=avg(kontrolniList);
document.getElementById("vezbe").innerHTML=avg(vezbeList);
document.getElementById("aktivnost").innerHTML=avg(aktivnostList);
document.getElementById("ocena").innerHTML=avg(ocenaList);
}
function avg( arr ) {
var total = 0, i;
for (i = 0; i < arr.length; i += 1) {
total += arr[i];
}
return total / arr.length;
}
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Dodaj ocenu</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick="javascript:calcMean();"> Izracunaj prosek</button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Kontrolni</td>
<td style="width:70px; text-align: center;">Vezbe</td>
<td style="width:70px; text-align: center;">Aktivnost</td>
</tr>
<tr>
<td id="kontrolni" style="text-align: center;"> </td>
<td id="vezbe" style="text-align: center;"></td>
<td id="aktivnost" style="text-align: center;"></td>
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Zakljucna ocena</td>
</tr>
<tr>
<td id="ocena" style="text-align: center;"> </td>
</tr>
</tbody>
</table>
</div>
Hope this will work.

Formatting currency and percentage in input field

I was only able to insert a "$" sign in a3. I also need to insert the "$" sign for a1 but when I insert format for a1 field in like this
$('#a3').val(format($('#a1').val(format) * $('#a2').val()));
I get an error. What is the best way to do this?
HTML
<table class="table">
<tbody>
<tr>
<td>You</td>
<td class="light-gray">Example</td>
</tr>
<tr>
<td width="20%">a1
<input type="textbox" class="form-control" id="a1" name="a1" />
</td>
<td width="20%" class="light-gray">$30,000</td>
</tr>
<tr>
<td>a2
<input type="text" class="form-control" id="a2" name="a2" />
</td>
<td class="light-gray">90%</td>
</tr>
<tr>
<td>a3
<input type="text" class="form-control" id="a3" name="a3" data-cell="a3" />
</td>
<td class="light-gray">$27,000</td>
</tr>
<tr class="heading">
<th colspan="2"> </th>
</tr>
</table>
jQuery
$(document).ready(function () {
var format = function (num) {
var str = num.toString().replace("$", ""),
parts = false,
output = [],
i = 1,
formatted = null;
if (str.indexOf(".") > 0) {
parts = str.split(".");
str = parts[0];
}
str = str.split("").reverse();
for (var j = 0, len = str.length; j < len; j++) {
if (str[j] != ",") {
output.push(str[j]);
if (i % 3 == 0 && j < (len - 1)) {
output.push(",");
}
i++;
}
}
formatted = output.reverse().join("");
return ("$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : ""));
};
$("#a1,#a2").keyup(function (e) {
$('#a3').val(format($('#a1').val() * $('#a2').val()));
});
});
JSFiddle Examples
Your problem is that you assume the values inside the inputs to be numbers. Since you format those with non-digit-characters they are not (and can not be casted to a number).
$('#a1').val() * $('#a2').val()
Since the values you are multiplying are no numbers an error is thrown.
To be able to multiply those strings (or to be exact the value they are representing) you need to unformat your strings before you can cast those to numbers and do your calculation!
You'll find an working example at https://jsfiddle.net/hn669das/18/.
By the way: Better use the change-event for formatting instead of the keyUp-event since the user won't be able to write into the input undisturbed when the input is manipulated while the user intends to write to it. The change-event will trigger when the input looses its focus and so won't disturb the user.
I hope that helps you!

JavaScript - Adding the new fields to existing ones

I am having a hard time with this homework.
Trying to keep adding the multiplication of the new 2 fields the user will add.
Example:
first field 5 second field 5 = total is 5*5 = 25
But when the user clicks the add field, he would have:
first field = 5 second field 5
first field = 6 second field 6 total would be 5*5 + 6*6 = 61 and so forth
<script>
function calc(form) {
var box1 = parseFloat (form.leftover.value,10)
var box2 = parseFloat (form.charge.value,10)
var temp = new Array();
var Mbalance = ( box1 * box2 ) ;
temp.push(Mbalance) ;
for ( var i=0; i< temp.length ; i++ ) {
Mbalance = Mbalance+Mbalance ;
}
form.mbalance.value= Mbalance ;
}
// This script is identical to the above JavaScript function.
var ct = 1;
function new_link(form) {
ct++ ;
var div1 = document.createElement('div');
div1.id = ct;
// Link to delete extended form elements
div1.innerHTML = document.getElementById('newlinktpl').innerHTML ;
document.getElementById('newlink').appendChild(div1);
}
</script>
</script>
<form>
<div id="newlink">
<div>
<td width="423">What was the balance left over from last month ?</td>
<td width="19">$</td>
<td width="141"><input name="leftover" value="" maxlength="10" /></td>
</tr>
<tr>
<td>How much did you charge this month ?</td>
<td>$</td>
<td><input name="charge" value="" maxlength="10" /></td>
<br/>
</div></div>
<button type="submit" id="buttoncalculate" onclick="calc(this.form); return false; "></button>
<br />
<td width="462">Monthly Balance</td>
<td width="128"><input name="mbalance" value="" maxlength="10" /></td>
Add new
</form>
<form>
<!-- Template -->
<div id="newlinktpl" style="display:none">
<div>
<td width="423">What was the balance left over from last month ?</td>
<td width="19">$</td>
<td width="141"><input name="leftover" value="" maxlength="10" /></td>
</tr>
<tr>
<td>How much did you charge this month ?</td>
<td>$</td>
<td><input name="charge" value="" maxlength="10" /></td>
</div>
</div>
<form>
Here's one way you can do it. It's not necessarily the best, but it achieves what you want and I don't feel like completely rewriting what you had:
http://jsfiddle.net/HS6dt/2/
I added a class to the parent div of your two inputs as well as your two inputs. That way I can find the parent div, then find the descendant inputs, get their values and multiple them (note: I have no idea why you are multiplying those two values, it really doesn't make much sense, but whatever):
function calc(form) {
var total = 0;
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) {
var left = items[i].getElementsByClassName("leftover");
var charge = items[i].getElementsByClassName("charge");
total += parseFloat(left[0].value, 10) * parseFloat(charge[0].value, 10);
}
form.mbalance.value = total;
}

Calculate percentage between dynamic number of inputfields

I need to display the percentage each input value contains out of the full dataset.
So if the user inputs 3, 2 and 1. The "percent" inputfield should show "50, 30 and 20"
The thing is, i dont know how many inputs the form will get. It could be from 1 to any number.
The source html code is created by a partial view i created. The output is:
<table>
<tr>
<th>Name</th><th>Distributiob key</th><th>Percent</th>
</tr>
<tr>
<td>
House 1
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_0__DistributionKey" name="LightPhysicalEntities[0].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_0__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 2
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_1__DistributionKey" name="LightPhysicalEntities[1].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_1__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 3
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_2__DistributionKey" name="LightPhysicalEntities[2].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_2__Percent" readonly=readonly />
</td>
</tr>
First field in the table is the title or name. Second is where the user punches in distribution number. Third is the readonly field with the calculated percentage.
The calculation should be done in javascript, but i cant quite crack the nut on how to get started, getting the inputs and setting the outputs.
A function like this should help (this will round down the percentages- replace the Math.floor if you want to handle differently):
function calcPcts() {
var distributions = $("[id$=DistributionKey]");
// Get the base first
var base = 0;
distributions.each(function () {
base += window.parseInt($(this).val(), 10);
});
// Now calculate the percentages of the individual ones
distributions.each(function () {
var input = $(this),
val = window.parseInt($(this).val(), 10),
pct = (val === 0) ? val : Math.floor((val / base) * 100);
$("#" + input.attr("id").replace("DistributionKey", "Percent")).val(pct);
});
}
If you add a class to the input fields you can use jQuery to get the number of items with that class. Then you can get the values and perform your calculations.
Here is an example:
var inputCount = $(".inputfield").length;
$("input[type='text']").change(function() {
var total = GetTotal();
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
if (total != 0) {
var percent = inputValue / total;
$('#LightPhysicalEntities_' + i + '__Percent').val(percent);
}
}
});
function GetTotal() {
var total = 0;
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
total += parseInt(inputValue);
}
return total;
}
Here is an example of the script working: http://jsfiddle.net/ZWuQr/

Categories