How can get last value of form charge in jQuery - javascript

I am trying to make a form where a customer can choose parson and automatically show the cost depend on parson number. So for that, I used jQuery form change function and calculate the cost inside of the function. My all logic is working ok but the issue is when increasing number then showing multiple costs.
Visual look:
Always I want to show the last one/ updated one
Blow my code:
var adultsSingleChage = 200;
var childrenSingleCharge = 100;
var infantsSingleCharge = 50;
$('#absbt_form input').change(function(){
var adults = $("#absbt_adults").val();
var adultsCharge = adults * adultsSingleChage;
var children = $("#absbt_children").val();
var childrenCharge = children * childrenSingleCharge;
var infants = $("#absbt_infants").val();
var infantsCharge = infants * infantsSingleCharge;
var totalCharge = adultsCharge + childrenCharge + infantsCharge;
console.log(totalCharge);
$('.total_cost').append(totalCharge);
});
I know I did the maximum of logic but for last logic, I'm confused.
How can I just show the last one?

append adds new content to existing one - that's the reason of having previous values.
Instead of using append use text:
$('.total_cost').text(totalCharge);

The problem is with the code you are appending which means you are adding the text into the element instead of replacing it. You can use the following two methods:
text(): $('.total_cost').text("iota")
html(): $('.total_cost').html("iota")
Note: Use id selector or with class use $($('.total_cost')[0])

Use html(totalCharge) instead of append(totalCharge)

Related

How to use two IDs from JS?

On my page with payment I need two inputs with total payment value:
- one that the client can see
- another one which is hidden.
I wrote a code which pass price of every element to the input when a client check a box with a product they want to pay for, but it works only with the one input.
I was trying to use different options (like getElementsByName and getElementsByClassName) but I am learning JS now and I have no idea how to solve this problem. :(
function select(selector, parent){
return Array.from((parent||document).querySelectorAll(selector));
}
var inputs = select('.sum'),
**totalElement = document.getElementById('payment-total');**
function sumUpdate(){
totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
WHAT I TRIED:
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total, payment-total2')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total).getElementsByName('payment-totalTwo);**
If I'm understanding you right, you want to put the computed value in both the id="payment-total" element and the id="payment-total2" element.
If so, just do what you've already done for payment-total, but for payment-total2 as well, see *** comments:
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total'),
totalElement2 = document.getElementById('payment-total2'); // ***
function sumUpdate(){
//vvvvvvvvvvvvvvvvvvvvvv---- ***
totalElement2.value = totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
I don't immediately see the reason for having both a visible and a hidden input, but if you need that for some reason, that's how you'd do it.
If it got to the point there were three or more elements you wanted to update, I'd probably give them all a class and select them the way you've selected your .sum elements, then compute the total once and assign it to all of them in a loop. But for just two, repeating the lookup and assignment seems fine.

Renaming formelements in a particular range with jquery

I've multiple autogenerated forms on a page. They are named in a particular manner like:
form-0-weight, form-1-weight, form-2-weight etc.
<ul>
<li>
<input id="id_form-0-weight" type="text" name="form-0-weight">
<a class="deleteIngredient" href="">x</a>
</li>
<li>
....more forms
</li>
</ul>
The user can add and delete forms. If a form get's deleted, the remaining ones should be renamed to stay in order. e.g. "form-1-weight" gets deleted >> "form-2-weight" will be renamed to "form-1-weight".
The total number of forms is stored in a hidden field named TOTAL_FORMS.
I'm trying to achieve this with a simple for loop.
The problem is that all the forms after the deleted one get the same name.
e.g. If I delete form-2-weight, all the following forms get the name form-2-weight instead of 2, 3, 4 etc.
$(".deleteIngredient").click(function(e){
e.preventDefault();
var delete = $(this).closest('li');
name = delete.children('input').attr("name");
count = name.replace(prefix,'');
count = name.replace("-weight",'');
var formCount = parseInt($("#TOTAL_FORMS").val())-1;
delete.remove();
for (var i = parseInt(count); i<=formCount; i++){
var newName = "form-"+i+"-weight";
$("#id_form-"+(i+1)+"-weight").attr("name",newName);
}
});
I suppose it has something to do with how I select the elements inside the loop because when I use just the variable "i" instead of "newName" it works as expected.
The problem is you're not initializing i properly.
This happens because "count" doesn't contain a string that can be parsed into an integer under the conditions of parseInt, I suggest you look here:
w3Schools/parseInt
Note: If the first character cannot be converted to a number, parseInt() returns NaN.
When you assign a string to "count" you're actually inserting the string "form-i" into the variable.
What you should do is this:
count = name.replace(prefix,'');
count = count.replace("-weight",'');
You should also rename your "delete" variable to "form" or any other descriptive name, as delete is a reserved word in javascript and also an action so it doesn't really suit as a name for an object.
Don't forget to change the id attribute of the item so it'll fit the new name.
As a note, you should probably consider following through some tutorial on Javascript or jQuery, Tuts+ learn jQuery in 30 days is one i'd recommend.
My first impulse is just to solve this a different way.
Live Demo
var $ul = $('ul');
// Add a new ingredient to the end of the list
function addIngredient() {
var $currentIngredients = $ul.children();
var n = $currentIngredients.length;
var $ingredient = $('<li>', {
html: '<input type="text" /> x'
});
$ul.append($ingredient);
renameIngredientElements();
}
// Rename all ingredients according to their order
function renameIngredientElements() {
$ul.children().each(function (i, ingredient) {
var $ingredient = $(ingredient);
var $input = $ingredient.find('input');
var name = 'form-' + i + '-weight';
$input
.attr('id', 'id_' + name)
.attr('name', name);
});
}
// Delete an ingredient
function deleteIngredient($ingredient) {
$ingredient.remove();
renameIngredientElements();
}
// Bind events
$('.add-ingredient').on('click', addIngredient);
$ul.on('click', '.delete-ingredient', function (event) {
var $ingredient = $(event.currentTarget).closest('li');
deleteIngredient($ingredient);
event.preventDefault();
});
As to why your particular code is breaking, it looks like user2421955 just beat me to it.

JavaScript Asp.net repeating controls

I am trying to do the folowing with Asp.net 3.5/IIS
A web form with a top level repeatable form. So basically a Order->Products->ProductsParts kinda of scenerio. Order is only one. Product is repeatable. Each product has repeatable products parts. The product and product part have a whole bunch of fields so I cannot use a grid.
So, I have add/remove buttons for Product and within each product add/remove buttons for each product part.
That is my requirement. I have been able to achieve add/remove after some research using jquery/js. How, do i capture this data on the server? Since javascript is adding and removing these controls they are not server side and I don't know how to assign name attributes correctly. I am trying following javascript but it ain't working:
function onAddProperty(btnObject){
var previous = btnObject.prev('div');
var propertyCount = jquery.data(document.body, 'propertyCount');
var newDiv = previous.clone(true).find("*[name]").andSelf().each(function () { $(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr)); }); ;
propertyCount++;
jquery.data(document.body, 'propertyCount', propertyCount);
//keep only one unit and remove rest
var children = newDiv.find('#pnlUnits > #pnlUnitRepeater');
var unitCount = children.length;
var first = children.first();
for (i = 1; i < unitCount; i++) {
children[i].remove();
}
newDiv.id = "pnlPropertySlider_" + propertyCount;
newDiv.insertBefore(btnObject);
}
I need to assign name property as array so that I can read it in Request.Form
Fix for not updating ids not working:
var newDiv = previous.clone(true).find("input,select").each(function () {
$(this).attr({
'name': function () {
var name = $(this).attr('name');
if (!name) return '';
return name.replace(/property\[[0-9]+\]/, 'property' + propertyCount);
}
});
}).end().insertBefore(btnObject);
The issue looks like the following line:
$(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr));
This statement doesn't do anything. Strings in JavaScript an immutable, and .replace only returns the string with something replaced.
You would then have to actually set the attr("name") to the new string that has the replaced value:
http://api.jquery.com/attr/
I can't help much more without seeing your HTML.

How to make two select forms of different ids and names return their ids using $(this)?

I have an html form with two select dropdown lists. Each one has the same sites that you leave from/go to. I'm trying to grab the ID of each one and store them as separate variables, but each time I select a new option, the variables reset to undefined. My code looks like this:
$('select[name=Depart], select[name=Return]').change(function(){
var id = $(this).attr('id');
var depart_id;
var return_id;
// Grabs the place you left from
var dep = $('select[name=Depart] option:selected').val();
// Grabs the place you traveled to
var ret = $('select[name=Return] option:selected').val();
// Grabs the day in the log as a string
var day_id_raw = $(this).closest('tr').attr('id');
// Creates a jQuery object from the string above
var day_id = $('#' + day_id_raw);
// Creates a substring of the string above cutting it off at the day number in the log. E.g. "Day 1" in the log becomes the number "1".
var day_num = day_id_raw.substring(3, day_id_raw.length);
//Creates a jQuery object for the miles of the day table column
var miles_today = $('#miles_day' + day_num);
if($(this).is($('select[name=Depart]'))){
depart_id = id;
}
if($(this).is($('select[name=Return]'))){
return_id = id;
}
// Checks if the place you left from contains a column to output how many miles you traveled that day.
if(day_id.has(miles_today)){
miles_today.text(depart_id + "\n" + return_id);
}
)};
The last if statement is just for debugging purposes. miles_today is a blank div that I'm writing content to in order to test if the variables are actually working. Like I said earlier, each time I change an option on either select input, the alternate variable is cleared. Thanks in advance.
EDIT: Sorry for the late reply and ambiguous wording. Here is a working example of what I have: http://jsfiddle.net/8xVuX/2/
Just enter 1 or 2 in the 'Number of days' field and it should add a new row. If you click the select menu for 'Departed From' and choose an option, it'll output its id in the field to the left, but undefined for the other field 'Returned To's id. I want to have both ids displayed when the select options are changed.
Get them outside the change function, and use them wherever you'd like :
var depart_id = $('select[name=Depart]').prop('id'),
return_id = $('select[name=Return]').prop('id');
$('select[name=Depart], select[name=Return]').on('change', function(){
miles_today.text(depart_id + "\n" + return_id);
});
but are you sure you should'nt be getting the value ?

Javascript's getElementById is not working in my loop

I have an issue with a function I have been working on. The purpose of this function is to take the dates that are inside two sets of text input boxes, calculate the difference between the two, and then place that number of days in a third set of boxes. My function is shown below.
function daysBetween() {
for (var i = 0; i < 8; i++) {
//Get the value of the current form elements
var start = namestart[i];
var end = namend[i];
var out = names[i];
//Duration of a day
var d = 1000*60*60*24;
// Split Date one
var x = start.split("-");
// Split Date two
var y = end.split("-");
/// // Set Date one object
var d1 = new Date(x[0],(x[1]-1),x[2]);
// // Set Date two object
var d2 = new Date(y[0],(y[1]-1),y[2]);
//
// //Calculate difference
diff = Math.ceil((d2.getTime()-d1.getTime())/(d));
//Show difference
document.getElementById(out).value = diff;
}
}
The three arrays referenced by the variables at the beginning contain simply the names of the form elements I wish to access. I've tested the start, end, and out variables with an alert box and the loop runs fine if I do not have the line under the Show Difference comment in the code. I have also gone through and made sure that all names match and they do. Also I have manually run the page eight times (there is eight sets of boxes) with each set of names and it successfully displays 'NaN' in the day box (I have no data in the source boxes as of yet so NaN is the expected behaviour).
When I run the function as shown here what happens is that the first set of text boxes works as intended. Then the loop stops. So my question is quite simple, why does the loop hangup with getElementById even though the names[0] value works, it finds the text box and puts the calculated difference in the box. The text box for names[1] does not work and the loop hangs up.
If you need more detailed code of my text boxes I can provide it but they follow the simple template below.
// namestart[] array
<input type="text" name="start_date_one" id="start_date_one" value=""/> <br />
// namend[] array
<input type="text" name="end_date_one" id="end_date_one" value=""/> <br />
// names[] array
<input type="text" name="day_difference_one" id="day_difference_one" value=""/>
Thanks for any help in advance.
Edit: Noticing the comments I figured I would add my array definitions for refernece. These are defined immediately above the function in my calcdate.js file.
var namestart = new Array ();
namestart[0] = "trav_emer_single_date_go";
namestart[1] = "trav_emer_extend_date_go";
namestart[2] = "allinc_single_date_go";
namestart[3] = "allinc_annual_date_go";
namestart[4] = "cancel_date_go";
namestart[5] = "visitor_supervisa_date_go";
namestart[6] = "visitor_student_date_go";
namestart[7] = "visitor_xpat_date_go";
var namend = new Array ();
namend[0] = "trav_emer_single_date_ba";
namend[1] = "trav_emer_extend_date_ba";
namend[2] = "allinc_single_date_ba";
namend[3] = "allinc_annual_date_ba";
namend[4] = "cancel_date_ba";
namend[5] = "visitor_supervisa_date_ba";
namend[6] = "visitor_student_date_ba";
namend[7] = "visitor_xpat_date_ba";
var names = new Array ();
names[0] = "trav_emer_single_days";
names[1] = "trav_emer_extend_days";
names[2] = "allinc_single_days";
names[3] = "allinc_annual_days";
names[4] = "cancel_days";
names[5] = "visitor_supervisa_days";
names[6] = "visitor_student_days";
names[7] = "visitor_xpat_days";
I reference the file and call my function in my header as such:
<script type="text/javascript" src="calcdate.js"></script>
<script type="text/javascript">
window.onload = daysBetween;
</script>
First and foremost, you can't reference an object by its ID when it doesn't have an ID.
<input type="text" id="start_date_one" name="start_date_one" />
since you say out contains a name you might want to change
document.getElementById(out).value = diff;
to
document.getElementsByName(out)[0].value = diff;
or you could actually just add the id attribute to your html and set it to the same value as the name attribute and you can avoid changing your javascript.
getElementById gets the element by its id attribute, getElementsByName gets all of the elements with the specified name attribute and returns it as an array. In HTML id is supposed to be unique which is why getElementById returns only 1 element

Categories

Resources