Autofill Amount - javascript

I have this split function which I can add more fields by clicking the button. My Problem are if I add a field I can't get the exact amount and back the amount if I remove the field.
Sample Scenario:
The above image show the initial amount -1,000.50. Now these are my problems.
I input 50 in the amount of first field which result to Payee: 1 [-950.50] as the remaining amount for payee. When I add another field it's auto fill the amount and I expect -950.50 because that's the remaining amount. But what I get is the initial amount -1,000.50 in the second field. How to get the updated remaining amount?
If I remove the added field I want to added back the amount. For ex. if the field has 50 and the remaining amount is -950.50. If I remove the field that contains amount of 50 it must be added back in the remaining amount and it will be -1,000.50. How to added back the amount?
Here are what I have tried:
split.html
<table id="dataTable" class="calendar fluid" data-calendar-options='{"maxHeight":70}'"
<caption> Payee: 1
[<span id="remaining">-1,000.50</span>]
</caption>
<tbody>
<tr>
<td class="week-end" id="p_scents"><br/>
*Note: Amount totals must equal transaction total and envelopes must be specified to
enable the split button.<br/><br/>
<p class="button-height">
<span class="input">
<label class="button orange-gradient">Envelope #1</label>
<select name="env[]" class="envelope select compact">
<option value="none">(Select)</option>
<optgroup label="Category">
<option value="1">Internet</option>
<option value="2">Savings</option>
</optgroup>
</select>
<input type="text" name="amt[]" placeholder="0.00" size="10"
id="validation-required" class="input-unstyled input-sep validate[required]"
onkeyup="calculate(0)">
<input type="text" name="note[]" placeholder="note" class="input-unstyled" id="note">
</span>
<span class="with-tooltip">
<img src="{{STATIC_URL}}img/icons/tick.png" title="Default">
</span>
</p><br/>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<a href="javascript:{}" id="addScnt" class="button orange-gradient icon-plus-round">
Another Envelope
</a>
</td>
</tr>
</tfoot>
</table>
<script>
function calculate(difference) {
var sum = 0;
$(":text").each(function() {
amt = replaceCommaDollar(this.value);
if(!isNaN(amt) && amt.length!=0) {
sum += parseFloat(amt);
total = sum;
difference = -1,000.50 + total
}
});
$("#remaining").html(numberWithCommas(difference.toFixed(2)));
if(difference == 0){
$("#split").html("<button type='submit' class='button orange-gradient'>Split Amount</button>");
}else{
$("#split").html("<button type='submit' class='button orange-gradient' disabled='disabled'>Split Amount</button>");
}
}
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
var remain_amount = Math.abs(replaceCommaDollar($("#remaining").text())).toFixed(2);
$('#addScnt').live('click', function() {
$('<p class="button-height">'+
' <span class="input">'+
' <label class="button orange-gradient">' + 'Envelope #' + i + '</label>' +
' <select name="env[]" class="envelope select compact">'+
' <option value="none" selected="selected">(Select)</option>' +
' <optgroup label="Category">' +
' <option value="1">Internet</option>' +
' <option value="2">Savings</option>' +
' </optgroup>' +
' </select>' +
' <input type="text" name="amt[]" id="split-amount' + i + '" placeholder="0.00" size="10" class="input-unstyled input-sep" onkeyup="calculate(0)" value="'+ remain_amount +'">'+
' <input type="text" name="note[]" placeholder="note" class="input-unstyled">'+
' </span>'+
' Remove</p><br/\>'
).appendTo(scntDiv);
$("#remaining").html('0.00');
$("#split").html("<button type='submit' class='button orange-gradient'>Split Amount</button>");
i++;
return false;
});
$('#remScnt').live('click', function() {
if( i > 2 ) {
test = $('#split-amount'+i).val();
alert(test);
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>

How to get the updated remaining amount? You are calculating remain_amount on document ready, instead of when you click the add button. You need to move its calculation within the click handler for #addScnt. Just make it the first line of that function and it should recalculate accordingly.
How to added back the amount? We can do this by reading the value out of the input field we are removing. Here is the modified remove click handler to demonstrate.
$('#remScnt').live('click', function() {
// Might not need the if statement
if (i > 2) {
//test = $('#split-amount' + i).val();
//alert(test);
var $p = $(this).parents('p');
// Consider this approach to getting the removed value
var textValue = $p.find('input[name="amt[]"]').val();
var numValue = replaceCommaDollar(textValue);
var $remaining = $("#remaining");
var remainingValue = replaceCommaDollar($remaining.text());
var difference = remainingValue - numValue;
var newRemainingValue = numberWithCommas(difference.toFixed(2)))
$("#remaining").text(newRemainingValue);
$p.remove();
// This might not be needed anymore
i--;
}
return false;
});
Note that given my approach to obtaining the removed value, you might be able to get rid of the logic involving i unless you have other work to do. Consider searching the DOM based on the element you're removing. This is probably slower to execute, but not unreasonably so. It's your choice though and it shouldn't matter too much either way. I think my suggestion is easier to maintain, and if I were to optimize there are other aspects of this page that deserve more attention.
I also recommend creating a functional jsFiddle in the future, your problem would have been much easier to test and solve with a functioning example. I tried creating one, but I had to alter the HTML and JavaScript too significantly, as there are missing JavaScript functions in the source you provided.
I hope that helps! Feel free to ask any questions regarding my answer, but please don't expand the scope of your original problem.

Related

jQuery Change number inside name attribute on cloned row with multiple inputs

I have a form row with 26 inputs on it, some text some select boxes. I have a button that clones the top row, adds an increment to the row number. However i'm struggling to work out how to increment the name and ID of the cloned field elements.
Form:
<tr id="CmasterRow" class="DB1_ROW">
<td><span id="cnumber"> <input type="text" size="2" readonly class="form-control" id="DB1[0][A]" name="DB1[0][A]" data-circuitNumber="0" data-EN="0" value="0"></span></td>
<td>
<div class="input-group">
<input type="text" class="form-control" id="DB1[0][B]" name="DB1[0][B]" data-EN="1">
</div>
</td>
<td>
<div class="input-group">
<input type="text" class="form-control" id="DB1[0][C]" size="2" name="DB1[0][C]" data-EN="2">
</div>
</td>
<td>
<input type="text" class="form-control" id="DB1[0][D]" size="4" name="DB1[0][D]" data-EN="3">
</td>
<td>
<div class="input-group">
<input type="text" class="form-control" id="DB1[0][E]" size="3" name="DB1[0][E]" data-EN="4">
</div>
</td>
<!-- ... etc ... etc ... -->
</tr>
Here's the javascript I have at the moment (the working on that clones the row)
var template = $('#CmasterRow'),
$("#addrow").click(function () {
var row = template.clone();
var n = $("[data-circuitNumber]").length;
row.find('input').val('');
row.find('[data-circuitNumber]').val(n);
row.find('input').attr('name').replace(/\[([0-9]+)\]/g,"[" + n + "]");
row.find('input').attr('id').replace(/\[([0-9]+)\]/g,"[" + n + "]");
row.insertBefore($('#disBoard tbody>tr:last').eq(-1));
// saveData(); - own function not needed for this issue.
return false;
/* Version 1 simple row clone
var row = $('#disBoard tbody>tr:first').clone(true);
var n = $("[data-circuitNumber]").length;
row.find('input').val('');
row.find('[data-circuitNumber]').val(n);
row.insertBefore($('#disBoard tbody>tr:last').eq(-1));
saveData();
return false;
*/
});
I 'think' I'm on the right lines with using the .find and the .replace and the regex. I am just a little stuck of getting it to work. I did get it working (of sorts) with a single form element however that java script has been chopped and changed with the above or i would have included that workings in this post.
Thanks for any help :)
To update an attribute for a node use:
var newValue = 'whatever'
row.find('selector').attr('your attribute', newValue);
Your code takes a value of an attribute, applies regex and then does nothing.
Javascript .replace does not replace anything in the original string and returns a new string with replaced values.
row.find('input').attr('name').replace(/\[([0-9]+)\]/g,"[" + n + "]");
row.find('input').attr('id').replace(/\[([0-9]+)\]/g,"[" + n + "]");
So the above lines basically return new values for id and name. you need to take those values and apply them as suggested by Eriks.
var newId=row.find('input').attr('name').replace(/\[([0-9]+)\]/g,"[" + n + "]");
var newName=row.find('input').attr('id').replace(/\[([0-9]+)\]/g,"[" + n + "]");
row.find('input').attr('id',newId);
row.find('input').attr('name',newName);
row.find('input').attr('id', function (i, val) {
val = val.replace(/\[([0-9]+)\]/g, "[" + n + "]");
return val
});
row.find('input').attr('name', function (i, val) {
val = val.replace(/\[([0-9]+)\]/g, "[" + n + "]");
return val
});
Thanks both for your help, I understand now where i was going wrong. I have completed the task by taking your input and developing the above code

Selecting a dynamically generated option element with a c# webbrowser control

I am using a c# webbrowser control to navigate through a commercial website I work with. I log in and navigate to a particular list. The list is prospective jobs. Then I continue through some links to bid on those jobs. In the process I ran into a problem.
On one of the forms there are 2 select elements (drop down lists). The options on those lists are generated dynamically by means of some javascript scripts - most of which are available in the source.
In the page source code there is nothing to select. The options appear dynamically when navigating the page manually - but I am trying to navigate it by means of c# in a webbrowser.
Here's the form. (I cut out styles and changed some of the text - and I know it is badly formed, but it is not mine)
<form name="frm1" id="frm1" action="/tab/Transport/LoadAssigned2.asp" method="post">
<table class="section">
<tr>
<td>Name</td>
<td>
<input type="text" name="s_name" id="s_name" size="25" maxlength="50"></td>
</tr>
<tr>
<td>Fax</td>
<td>
<input type="text" name="txtFaxNumber" id="txtFaxNumber" size="25" maxlength="15" value="1234567890"></td>
</tr>
<tr>
<td>Email</td>
<td>
<input type="text" name="txtEmail" id="txtEmail" size="25" maxlength="225"></td>
</tr>
<tr>
<td>Pickup will occur on or before</td>
<td>
<select name="stransp_pickup_date" id="stransp_pickup_date" style="width: 173px;" onchange="setDeliveryDate()">
</select>
</td>
<tr>
</tr>
<td>Delivery will occur on or before</td>
<td>
<select name="stransp_delivery_date" id="stransp_delivery_date" style="width: 173px;">
</select>
</td>
</tr>
</table>
<input type="hidden" name="nload_id" id="nload_id" value="123456789">
</form>
As you can see the two select elements have no option children. Those are created by the scripts, starting with setDeliveryDate:
function setDeliveryDate(){
var distance = 226;
var delivery = $("#stransp_delivery_date");
var pickupDate = $("#stransp_pickup_date option:selected").val();
$("#stransp_delivery_date option").remove();
delivery.append("<option value='-1'>SELECT DATE</option>");
if(distance <=200){
generateDeliveryDates(delivery,pickupDate,2);
}else if(distance >=201 && distance <= 400){
generateDeliveryDates(delivery,pickupDate,3);
}else if(distance >=401 && distance <= 700){
generateDeliveryDates(delivery,pickupDate,4);
}else if(distance >=701 && distance <= 1400){
generateDeliveryDates(delivery,pickupDate,5);
}else if(distance >=1401 && distance <= 1800){
generateDeliveryDates(delivery,pickupDate,6);
}else if(distance >=1801 && distance <= 2200){
generateDeliveryDates(delivery,pickupDate,7);
}else if(distance >=2201 && distance <= 2500){
generateDeliveryDates(delivery,pickupDate,8);
}else if(distance >=2501 && distance <= 4000){
generateDeliveryDates(delivery,pickupDate,9);
}
}
And the generateDeliveryDates functions is:
function generateDeliveryDates(delivery,pickupDate,index){
for (var i = 0; i < index; i++) {
if (moment(pickupDate).add('days', i).format('dddd') == 'Sunday') {
index++;
delivery.append("<option value='" + moment(pickupDate).add('days', i).format('MM/DD/YYYY') + "'>" + moment (pickupDate).add('days', i).format('dddd')+" - "+ moment(pickupDate).add('days', i).format('MM/DD/YYYY') + "</option>");
} else {
delivery.append("<option value='" + moment(pickupDate).add('days', i).format('MM/DD/YYYY') + "'>" + moment (pickupDate).add('days', i).format('dddd')+" - "+ moment(pickupDate).add('days', i).format('MM/DD/YYYY') + "</option>");
}
};
}
IfI can keep showing more of the scripts - but I'm hoping the idea is clear. The options under the select element are created based on an onchange event in the first select element. It is a list of dates.
What I want to do is to select the last of the date options in both cases - but I can't see how to do it before the exist. Also, the number of options in the list varies based on the distance, as you can see above.
How can I access those elements when I can't see them in the page source code?
Very appreciative of any help or guidance.
In case anyone reads this in the future, I ended up solving this myself, and want to share the solution, which is pretty straight forward.
1 - please note that the first "select" element has an onchange function- setDeliveryDate. So the first think I do is invoke that script function once:
webBrowser1.Document.InvokeScript("setDeliveryDate");
Then I collect the child nodes in a collection, and select the last of them:
HtmlElementCollection colOptions =
webBrowser1.Document.GetElementById("stransp_pickup_date").Children;
int colCount = colOptions.Count;
colOptions[colCount - 1].SetAttribute("selected", "selected");
The I re-run the same script, which also creates the options for the second select, and do the same thing (get the option elements into a collection and select the last one):
webBrowser1.Document.InvokeScript("setDeliveryDate");
HtmlElementCollection colOptions2 =
webBrowser1.Document.GetElementById("stransp_delivery_date").Children;
int colCount2 = colOptions2.Count;
colOptions2[colCount2 - 1].SetAttribute("selected", "selected");
The last step is of course to submit the form:
webBrowser1.Document.GetElementById("frm1").InvokeMember("submit");
Hope this helps other newbies like me.

Fields calculating only after a refresh

I apologize in advance for what I assume is a very basic question, but I am very new to scripting and would like to ask for some advice on a problem I am having.
Essentially I am creating a website that should sum the dollar amounts of two fields based on hours worked and return a total dollar amount. One of the fields has a fixed dollar amount and the other is a variable.
As far as I can tell the code should be working, but the field that should be user generated (esceptionalRate) seems to calculate correctly only after a page refresh, and then only on firefox... instead of automatically updating the total value when a change is made to the user field
code as follows:
<head>
</head>
<body>
<script>
$(document).ready(function () {
var standardRate = 110;
var exceptionalRate = $("#ex_rate").val();
var standardEntry = 0;
var exceptionalEntry = 0;
var totalVal = 0;
$("#Standard").on("change",function(){
standardEntry = $(this).val() * standardRate;
totalVal = standardEntry + exceptionalEntry;
$("#Amount").val(totalVal);
});
$("#Exceptional").on("change",function(){
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});
</script>
and here's the HTML side:
<input name="Standard" type="number" step="any" value="0" id="Standard" size="10" />
<input type="text" size="10" name="ex_rate" id="ex_rate" />
<input name="Exceptional" type="number" step="any" value="0" id="Exceptional" size="10" />
<td valign="top" nowrap="nowrap"><font size="2">Total Amount Requested </font></td>
<td><input name="Amount" type="text" id="Amount" size="35"/></td>
thanks in advance for all your wisdom and knowledge.
You have forgotten to close the $(document).ready function
Try:
$(document).on("change", "#Standard", function(){
And:
$(document).on("change", "#Exceptional", function(){
The problem is that your exceptionalRate variable is out of the scope of your calculation, and only gets set to the initial value upon the page loading. You need to move it within the change handler:
$("#Exceptional").on("change",function(){
exceptionalRate = $("#ex_rate").val();
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});

using conditionals with drop down menus in javascript

var macTeamList = "Team" + "<br>";
var macScoreList = "Score" + "<br>";
var nicTeamList = "Team" + "<br>";
var nicScoreList = "Score" + "<br>";
$('form').submit(function(e) {
if ($('input[name="Player1"]').val() ==="Nic") {
e.preventDefault();
var nicTeamValue = $('input[name="Team1"]').val();
nicTeamList += nicTeamValue + "<br>" ;
var nicScoreValue = $('input[name="Score1"]').val();
nicScoreList += nicScoreValue + "<br>";
$('#nicteamcolumn').html(nicTeamList);
$('#nicscorecolumn').html(nicScoreList);
return false;
}
else if ($('input[name="Player1"]').val() === "Mac") {
e.preventDefault();
var macTeamValue = $('input[name="Team1"]').val();
macTeamList += macTeamValue + "<br>" ;
var macScoreValue = $('input[name="Score1"]').val();
macScoreList += macScoreValue + "<br>";
$('#macteamcolumn').html(macTeamList);
$('#macscorecolumn').html(macScoreList);
return false;
}
})
<form>
<input name="foo" id="team" class="teamcolumn" type="text" value="Team?">
<input name="foobar" id="score" class="inputright" type="text" value="Score?">
<input type="submit" value="Go">
<select name="select" size="1" id="PID">
<option value="Nic">Nic</option>
<option value="Mac">Mac</option>
</select>
</form>
<div id ="nicteamcolumn" class="teamcolumn TOSRcolumn nicColumn">Team </div>
<div id="nicscorecolumn" class="scorecolumn TOSRcolumn nicColumn">Score</div>
<div id="macteamcolumn" class="teamcolumn TOSRcolumn macColumn">Team </div>
<div id="macscorecolumn" class="scorecolumn TOSRcolumn macColumn">Score</div>
Basically, I am having the user input 2 text values as well as choose from 2 options on a drop down menu. If the user chooses "Mac" the info in the two fields should print to #macscorecolumn and #macteamcolumnand vice versa if they choose "Nic". The list variables are keeping track of the whole list of scores so the new score is simply added to the end and they're all shown. Not sure why the script isnt working. Any help would be awesome
First of all, your code actually needs a rewrite :)
You don't need to submit a form to do this kind of thing, you could merely add either a link or a button (for GO), add a click function to it, and do your stuff in there.
Also I agree with Kunal that your syntax for the if statement is incorrect etc.
Just practice some more and remember that the jquery docs is your friend... :)
Here is your code I modified a little bit to make it work for you. But remember, you don't need a form for this, I just didn't have time to rewrite it differently for you. I also included jquery library just in case you missed that, which is critical.
<form>
<input name="foo" id="team" class="teamcolumn" type="text" value="Team?">
<input name="foobar" id="score" class="inputright" type="text" value="Score?">
<button id="dostuff" value="Go">Go</button>
<select name="select" size="1" id="PID">
<option value="Nic">Nic</option>
<option value="Mac">Mac</option>
</select>
</form>
<div id ="nicteamcolumn" class="teamcolumn TOSRcolumn nicColumn">Team </div>
<div id="nicscorecolumn" class="scorecolumn TOSRcolumn nicColumn">Score</div>
<div id="macteamcolumn" class="teamcolumn TOSRcolumn macColumn">Team </div>
<div id="macscorecolumn" class="scorecolumn TOSRcolumn macColumn">Score</div>
<script src="js/jquery-1.6.4.min.js"></script>
<script>
var macTeamList = "Team" + "<br>";
var macScoreList = "Score" + "<br>";
var nicTeamList = "Team" + "<br>";
var nicScoreList = "Score" + "<br>";
$('#dostuff').click(function(e) {
e.preventDefault();
var teamvalue = $('input[name="foo"]').val();
var teamscore = $('input[name="foobar"]').val();
var pidType = $("#PID").val();
if (pidType =="Mac") {
nicTeamList += teamvalue + "<br>" ;
nicScoreList += teamscore + "<br>";
$('#nicteamcolumn').html(nicTeamList);
$('#nicscorecolumn').html(nicScoreList);
}
else {
macTeamList += teamvalue + "<br>" ;
macScoreList += teamscore + "<br>";
$('#macteamcolumn').html(macTeamList);
$('#macscorecolumn').html(macScoreList);
}
});
</script>
You have used else if condition
Its condition element you have to put some condition
else if{ } // syntax error
else if("somethign goes in here"){ // your code } // correct way
and over here only else can do the thing
You have putted ; at the block end of if statement and and the block end of else. Syntax error

How to select a input field in next TD with Jquery?

I want to select a input field in next TD with Jquery. I can not use ID or class because the table's row can be add or removed.
like ,
<tr>
<td><input type='text' name='price[]' onkeyup = 'getTest(this)' /> </td>
<td><input type='text' name='qty[]' onkeyup = 'getPrice(this)' value='1' /> </td>
<td><input type='text' name='amount[]' /> </td>
</tr>
function getTest(obj){
//I want to select qty[] and amount[]
}
function getPrice(obj){
//I want to select price[] and amount[]
}
anybody know how to select the input fields, please help~!
Thanks
working demo of your expected behavior of your webpage.
Chinmayee's answer is much better than this one, but if you don't want to change any of your HTML mark-up, you can simply drop this into your JavaScript and it will work:
function getTest(obj) {
var tr = $(obj).closest('tr');
var qty = tr.find('input[name="qty[]"]');
var amount = tr.find('input[name="amount[]"]');
console.log('qty: ' + qty.val());
console.log('amount: ' + amount.val());
}
function getPrice(obj) {
var tr = $(obj).closest('tr');
var price = tr.find('input[name="price[]"]');
var amount = tr.find('input[name="amount[]"]');
console.log('price: ' + price.val());
console.log('amount: ' + amount.val());
}
But the reason why Chinmayee's answer is better than mine is because it uses unobtrusive JavaScript, and it also uses event delegation, so it will perform better.
Here's a possible solution for your problem (assuming you want amount to be price * qty):
$(document).ready(function(){
$('[name="price[]"], [name="qty[]"]').live('keyup', function(){
var inputs = $(this).closest('tr').find('input');
$(inputs[2]).val($(inputs[0]).val()*$(inputs[1]).val());
});
});
Your getTest() and getPrice() methods are no longer required with this solution and you can also drop the onkeyup="..." attributes on the input elements.
See here for a working demo.

Categories

Resources