How to make an offer code field within a form? - javascript

I have the following form:
http://jsfiddle.net/GZYKQ/
How would I make it so that when the user inputs "DISCOUNT10" (in capitals or lowercase) the jquery script takes 10% off the repair price? Not the total price, the repair price which is at the top of the form (var price).
The script should then add the repair price (minus the 10%), the outward postage price, and the return postage price and display the total.
I have no experience with jQuery so this code probably has a lot wrong with it but this is what I have:
$("button.offerapply").click(function() {
if (("input[name='offercode']").val = "DISCOUNT10"){
price = (price/100)*90;
}
Any help is greatly appreciated!

You're missing an extra =. Right now, you have an assignment. You want to compare the two values. The comparison operator is ==.
Try this:
$("button#offerapply").click(function() {
if ($("input[name='offercode']").val() == "DISCOUNT10"){
price = (price/100)*90;
$('.tot_price').html('£' + price);
}

$("#offerapply").click(function() {
if ($("#offercode").val() === "DISCOUNT10"){ //offercode is an id, not a name
price = (price / 10) * 9;
$('.tot_price').html('£' + price);
}
}
Notice that offercode is the ID of the input, not the name(JSFiddle here).

You're also missing the jQuery call in front of the input reference:
if ($("input[name='offercode']").val == "DISCOUNT10"){

Looking at your jsfiddle I would probably take
var tot_price = price + postage_out + postage_in;
and change it to have another variable:
var tot_price = (multiplier * price) + postage_out + postage_in;
multiplier would default to 1 and can change to say .90 if they enter the discount on the apply button.
http://jsfiddle.net/GZYKQ/3/

Related

find the value of the div then PLUS that numeric value to another div

I have 2 div's.
One is SHIPPING and another is TOTAL PRICE.
<div id="tt_shipping_rate_basket">$0.00</div> = SHIPPING
<div class="op_col5_3" align="right" id="tt_total_basket">$897.00</div> = TOTAL PRICE
Also there are 4 inputs for SHIPPING, each adds it's own price in the shipping div..
for example:
input 1 = 10$
input 2 = 20$
so when choosing an input the value in the #tt_shipping_rate_basket is changing ajax to the value of the input... this works great...
The problem is, I do not want 2 divs (one for shipping and one for total price)...
I just want ONE div, called Total Price, and when I choose an input, the value should ADD&CHANGE to the #tt_total_basket instead of tt_shipping_rate_basket...
What I'm trying to do is, GET the value of SHIPPING field (which is ajax populated), GET the value of TOTAL PRICE field, then just ADD shipping to Total Price...
here is what I tried to write but it doesn't seem to work, sorry I'm not to good at programming..
function plus() {
var spTotal = document.getElementById("tt_total_basket");
var spShip = document.getElementById("tt_shipping_rate_basket");
spTotal = spTotal.innerHTML = +spShip;
}
spTotal is the TOTAL PRICE
spShip is the Shipping Price
The result should be (spTotal = spTotal.value + spShip.value)..
Can somebody please help?
Untested, but you get the idea:
var spTotal = document.getElementById("tt_total_basket").innerHTML.replace('$', '');
var spShip = document.getElementById("tt_shipping_rate_basket").innerHTML.replace('$', '');
spTotal = parseFloat(spTotal) + parseFloat(spShip);

Real time accounting changes with jQuery

I'm trying to have a label which contains a balance change when a person enters a charge amount. So assume something like...
<table>
<tr>
<td class="remainingBudget"></td>
.
.
.
...and then....
<form>
<table>
<tr>
<td><input class="percentCommitment"></td>
<td><input class="totalAmount"></td>
.
.
.
The user will never touch the totalAmount form input, only percentCommitment, which will calculate totalAmount based on another value, which we don't need to worry about. I have the totalAmount input populating automatically on the keydown event of percentCommitment with something like this...
$(".percentCommitment").keyup(function() {
var commit = caluculatePercentCommitment() || 0;
var salary = getSalary();
var amount;
if (commit > 0 && salary > 0) {
ttl = (salary * commit) / 100;
} else {
amount = 0.00;
}
$(this).parent().find('.amountCommitment').val(amount);
});
This part is working fine and the total amount calculates correctly in real time as the person changes the percentCommitment value. This works because the value I multiply the percent commitment by, the person's annual salary, is static. It doesn't change. So if the person enters 1, 1% of salary is calculated and displayed. If the user then tacks on a 2, 12% is calculated from the same original salary, and this is exactly what I want to happen.
The problem comes with calculating the remaining budget in real time. Subtracting totalAmount from remainingBudget poses a problem, because if the user does the same thing, enters 1, then my jQuery does newRemainingBudget = remainingBudget - (0.01 * salary), which is fine, but then if they tack on a 2 I'm doing newNewRemainingBudget = newRemainingBudget - (0.12 * salary), which isn't what I want. I want all changes to be computed from the original remaining budget.
I was trying to do something like this...
$(".totalAmount").change(function (event) {
var remain = $(".remainingBudget").text();
remain = formatDecimalInput(remain);
var enter = $(".totalAmount).val();
enter = formatDecimalInput(enter);
if (enter <= remain) {
$(".remainingBudget")text((remain-enter).formatCurrency());
}
else {
// Do nothing
event.preventDefault();
}
});
You have to have a place on the screen that holds the total budget amount and calculate remaining amount using it plus the other fields. Don't use a field in this way when you are replacing.
remainingBudget = totalBudget - (0.01 * salary)
Note: You can have a hidden form field to hold the total if you want.

Why can't I set my input field with MooTools?

Ive got a document and when the user enters something into one input I need to show a response in a second input box. I can get the user given value, i can process it, but when I try to set the second input box with the result I get the error $.field is null. Here is the code:
$('places').addEvent('keyup', function(){
var places = $('places').value;
alert("PLACE: "+places);
var price = values[places];
var nights = $('nights').value.toInt();
alert("NIGHTS: "+nights);
var total = price * nights;
alert("TOTAL: "+total);
$('pricepernight').set('text', total);
$('pricetotal').set('text', total - ((total / 100) * 21));
});
So I get the place value. I pull the price of the place out of an assoc array. I then multiple that price by the amount of nights field in by the user and this is then my total amount. It is this amount that I cannot set to. Note that the alert shows the correct amount.
and the html looks like this
<div class='block'>
<input type="text" id="places" />
</div>
<div class='block'>
<label for="nachten">Aantal nachten</label>
<input type="text" id="nights" />
</div>
<div class='block long'>
<span class='label'>Prijs per slaapplaats per nacht</span>
<input type="text" class='resultfield' id='pricepernight' />
</div>
<div class='block last'>
<span class='label'>Totaalprijs excl. btw</span>
<input type="text" class='resultfield' id='pricetotal'/>
</div>
Firebug responds:
String contains an invalid character
[Break On This Error]
...x:\'4W\',3X:18.1l,al:18.1l,1Q:18.1l,as:18.1l,8S:18.1l,1F:O,3E:{x:\'1u\',y:\'1o\'...
Any ideas/suggestions anyone? Thank you in advance!
right. you seem to have used a mix of mootools and jquery code.
$('nights').addEvent('keyup', function(){
var places = $('places').value;
var price = values[places];
var nights = $('nights').value;
var total = price * nights;
alert(total);
$('#pricepernight').val(total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
in mootools 1.2+, this should be:
$('nights').addEvent('keyup', function(){
var places = $('places').get('value');
var price = values[places];
var nights = $('nights').get('value');
var total = price * nights;
alert(total);
$('pricepernight').set('value', total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
there's an implied global array values. also, this is not very safe as nights may not be integer.
the point is. #id -> id and .val() -> set('value', 'newvalue') - or .get('value')
There are couple of minor mistakes here.
First, you should use # sign to select based on your id attributes
like places and nights
Check http://api.jquery.com/id-selector/
Second, use val() to read the value from the html controls rather
than value
Check http://api.jquery.com/val/
try this
$('#nights').keyup(function(){
var places = $('#places').val();
var price = values[places];
var nights = $('#nights').val();
var total = parseInt(price) * parseInt(nights);
alert(total);
$('#pricepernight').val(total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
and what is values[places]?

allow user to type in 1 or more quantity using jquery?

I have the following code:
quantity = $('div.ProductNameText').text().match(/Exclusive Handmade Box/g).length;
if(quantity)
{
$("#kitProduct #Quantity").attr("value", quantity);
}
I would like to make it so that the user can enter 1 or MORE.
At the moment it forces the quantity box to display ONLY 1.
Any ideas?
edit: more info: the div class is the product title and im just trying to check that product exists then allowing the user to enter 1 or MORE into the quantity text box.
$("#kitProduct #Quantity").keyup(function() {
var quantity = parseInt($.trim($(this).val()));
if (!quantity || qantity < 1 || !quantity.length) {
$(this).val('1');
} else {
$(this).val(quantity);
}
});
PD, I believe that
quantity = $('div.ProductNameText').text().match(/Exclusive Handmade Box/g).length;
Will only return 1 for any single quantity 1,2,3,4,5,6,7,8,9. You are checking the length of the text; not the value of it.

Problem with running totals in jquery

I'm having an issue trying to get an accurate running total for my calculations. When you enter numbers into the input field I get an accurate total for that line item, but the grand total comes out to a higher number. Note that this is a dynamic form and that the id's will change depending on how many form fields I have added to the form. Also, I have it set to make the calculations onKeyUp for each input field instead of a calculate button.
The code that calculates a single item is this:
function calcLineItem(id) {
var id = $(id).attr("id");
var Item1 = $("#Item1" + id).val();
var Item2 = $("#Item2" + id).val();
var Item3 = $("#Item3" + id).val();
function calcTotal(Item1, Item2, Item3){
var total;
total = Math.round((Item1 * Item2) * Item3);
return total;
}
$("#total" + id).text(calcTotal(Item1, Item2, Item3));
calcAllFields();
}
This will give me the total of this particular input field. The function at the end, calcAllFields(), is supposed to do the calculations for all items in my form to give me the grand total of all input fields:
function calcAllFields(id) {
var id = $(id).attr("id");
$('#target1').text($("#total" + id).map(function() {
var currentValue = parseFloat(document.getElementById("currentTotal").value);
var newValue = parseFloat($("#total" + id).text());
var newTotal = currentValue + newValue;
document.getElementById("currentTotal").value = newTotal;
return newTotal;
}).get().join());
}
The variable currentTotal is getting its value from a hidden field on my form:
<input type="hidden" id="currentTotal" value="0">
As I enter numbers a field the calculation for that line will be accurate, but the grand total will be inaccurate because the value for currentTotal will continue to increment with every key stroke I make in the input field. Any ideas on how to avoid this from happening?
UPDATE: An example of what the form input fields would look like:
<tr id="row1">
<td><input type="text" id="field_1 onKeyUp="calcLineItem("#row1")></td>
<td><input type="text" id="field_2 onKeyUp="calcLineItem("#row1")></td>
</tr>
I hope this helps.
It appears that you are never removing the previous total when you calculate the grand total. For instance,
I start out with a grand total of 0. I change ID1 and get a total of 700. Now my grand total is 700. However, with your code, if I change ID1 again and set to 680, my grand total will be 1380 (700 + 680).
You should probably start with 0 and loop through all the totals again on calcGrandTotal() in order to pick up all client changes or track the previous total before you calculate the new line item total so that you can properly deduct it from the grand total. Also, if you have a lot of line items adding up to your grand total, you may consider only calling the calcGrandTotal() when on of your textboxes loses focus, else you could have a lot of JS calculations going on in the background which will interfere with animations and overall responsiveness of your site.
How's this?
function calcAllFields(id) {
var id = $(id).attr("id");
document.getElementById("currentTotal").value = 0; //reset the total as it will be caluclated next
$('#target1').text($("#total" + id).map(function() {
var currentValue = parseFloat(document.getElementById("currentTotal").value);
var newValue = parseFloat($("#total" + id).text());
var newTotal = currentValue + newValue;
document.getElementById("currentTotal").value = newTotal;
return newTotal;
}).get().join());
}
I would go about it slightly differently. You will need a function that returns the total for a row (Looks like calcLineItem pretty much does it, just remove the calcAlffields call. Add a class like calcrow to each row that needs to be totaled. Than just do something like this
function updateTotal () {
total = 0;
$.each($(".calcrow"), function(index, value) {
total += calcRow($(value).attr("id"));
});
$("#currentTotal").value(total);
}
Another if you don't want to calc each line again (it looked like you were storing a row total somewhere) have the row update function update the row total and than call this updateTotal.
function updateTotal () {
total = 0;
$.each($(".rowtotal"), function(index, value) {
total += $(value).attr("id");
});
$("#currentTotal").value(total);
}

Categories