second javascript not working on my contact form - javascript

Ok, all, I have a few questions.
How can I have my total have a $ and how can I move up next to the word Total: ( so it will be side by side)
Once I get a total price, is there a way where I can divide it by 2 to get 1/2 of the price into another field called 'deposit' before copying that to add to another field called 'balance':
I cannot get the date fields to copy
To note this is where I found how to add up the radio buttons ( Here)
This is what I have so far.
This is my form:
Session Date: <input type="text" name="field1" id="f1" />
Session Type payment :
<input type="radio" name="sessiontypepayment" id="sessiontypepayment1" value="100.00" onclick="FnCalculate(this,'extrapeople');"> Mini Session $100.00
<input type="radio" name="sessiontypepayment" id="sessiontypepayment2" value="250.00" onclick="FnCalculate(this,'extrapeople');"> Full Session $250.00
Extra people :
<input type="radio" name="extrapeople" id="extrapeople1" value="25.00" onclick="FnCalculate(this,'sessiontypepayment');"> 1 person $25.00
<input type="radio" name="extrapeople" id="extrapeople2" value="50.00" onclick="FnCalculate(this,'sessiontypepayment');"> 2 people $50.00
<input type="radio" name="extrapeople" id="extrapeople3" value="75.00" onclick="FnCalculate(this,'sessiontypepayment');"> 3 people $75.00
<input type="radio" name="extrapeople" id="extrapeople4" value="100.00" onclick="FnCalculate(this,'sessiontypepayment');"> 4 people $100.00
Total Amount: <div id="total"></div>
Deposit Amount:
Balance Amount:
balance due BY: <input type="text" name="field2" id="f2" />
This is my script what I have so far.
<script type="text/javascript">
$(document).ready(function(){
$("#f1").keyup(function(){
var f2Text = $('#f2').val() + $(this).val();
$('#f2').val(f2Text );
});
});
</script>
<script>
function FnCalculate(id,name)
{
var total=0;
if(document.getElementById(name+"1").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
if(document.getElementById(name+"2").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
total = total + parseInt(id.value);
document.getElementById("total").innerHTML = total;
}
</script>
I would really love help on this please.

First, get rid of all the onclick="FnCalculate(this,'xx');" bits on your inputs.
Then replace your <script>s with this:
<script type="text/javascript">
$(document).ready(function() {
$("#f1").keyup(function() {
$('#f2').val($(this).val());
});
var inputs = $('input[name="sessiontypepayment"], input[name="extrapeople"]');
$(inputs).click(function() {
var total = 0;
$(inputs).filter(':checked').each(function() {
total = total + parseInt($(this).val());
})
$('#total').html('$' + total);
$('#deposit').html('$' + (total / 2));
});
});
</script>
Unsure what you mean by "how can I move up next to the word Total" but I suspect changing <div id="total"></div> to <span id="total"></span> will solve your problem. Either that, or apply some css to the div:
#total {
display: inline;
}
I added the calculation for the deposit, you'll need to add <div id="deposit"></div> to your page somewhere...
You will need jquery. Add this in between <head>...</head>:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

First, you should have your defaults set to checked='checked' for HTML radio buttons that you want checked initially. I would put default text into <div id='total'>$125.00</div>, as well. You might as well use jQuery for what it's made for and not put Events into your HTML at all. .val() returns a String. To cast a String to an integer put + in front of it. To cast to a floating point Number use parseFloat().
$(function(){
$('#f1,[name=sessiontypepayment],[name=extrapeople]').change(function(){
$('#total').text('$'+(parseFloat($('[name=sessiontypepayment]:checked').val())+parseFloat($('[name=extrapeople]:checked').val())).toFixed(2));
$('#f2').val($('#f1').val());
});
});
To divide by 2 it's /2
As a newbie you should get into the practice of using external <script src so it will get cached into your Browser Memory, for faster load time when your Client revisits your site.

Related

Dynamically sum 2 fields on an MVC Edit form

I have an MVC Edit form with 2 fields called ExVAT and VAT. I want to add another field with the total of these 2 values.
At the moment what I have shows the total of the 2 fields when the form is loaded. But if you were to change one of the other fields the total is not updated to reflect the new total.
So for example in the screen shot below:
I have changed the Ex.Vat Figure from 22 to 32, but the total has not been updated (I'll deal with formatting when the value is correct)
The code to get the total is:
#Html.Raw(Model.Vat + Model.ExVat)
What is the best way to make the total field update as the other fields are edited?
JSFiddle: https://jsfiddle.net/3tnjtLv5/1/
<div>
<div><input id="txtA" type="text" value="1"></div>
<div><input id="txtB" type="text" value="2"></div>
<div id="txtResult">
</div>
<script>
var txtA=$('#txtA');
var txtB=$('#txtB');
var txtResult=$('#txtResult');
function updateSum() {
txtResult.html(parseInt(txtA.val()) + parseInt(txtB.val()));
}
$(function() {
updateSum();
txtA.change('change', updateSum);
txtB.bind('change', updateSum);
});
</script>
Use jQuery input, property change method
jQuery('#Ex.vat', '#vat').on('input propertychange paste', function() {
$('#Total').val($('#Ex.vat').val()+$('#vat').val());
});

Can't get if/else function to work with radio buttons

I have looked all over this site (and Google) for an answer to my problem but I can only seem to find bits and pieces, nothing specific.
I am primarily playing around with JavaScript and HTML but am not trying to use jquery right now.
So, with that said, this is what I'm trying to do: I would like the user to enter two numbers, select an operation (add, subtract, multiply, divide) out of a list of four radio buttons, and then click a button which is linked to a function that does the math and then presents it in a text box on the page. How would I do this using only HTML and JavaScript? I have gotten everything to work up until the point I add the radio buttons.
The code is as follows:
<script>
function operationForm (form) {
var x = document.operationForm.getElementById("numberOne");
var y = document.operationForm.getElementById("numberTwo");
var operation;
var answer;
if (document.operationForm.addSelect.checked === true) {
answer = x + y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.subtractSelect.checked === true) {
answer = x - y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.multiplySelect.checked === true) {
answer = x * y;
document.operationForm.answerBox.value = answer;
} else(document.operationForm.divideSelect.checked === true) {
answer = x / y;
document.operationForm.answerBox.value = answer;
}
}
</script>
<h1>Let's calculate!</h1>
<form name="operationForm">
<p>
<label>Enter two numbers, select an operation, and then click the button below.
<p>
<label>Number One:
<input type="text" name='numbers' id="numberOne">
<br>
<br>Number Two:
<input type="text" name='numbers' id="numberTwo">
<p>
<input type="radio" name="operations" id="addSelect" value=''>Add
<input type="radio" name="operations" id="subtractSelect" value=''>Subtract
<input type="radio" name="operations" id="multiplySelect" value=''>Multiply
<input type="radio" name="operations" id="divideSelect" value=''>Divide
<label>
<p>
<input type="button" value=" Calculate " onClick='operationForm(form);'>
<p>
<label>Your answer is:
<input type="text" name="answerBox">
If anyone has any fixes or can point me in the right direction of the correct syntax for handling radio buttons, functions linking to them, and onClick events linking to those functions, it would be extremely appreciated.
Consider replacing the <input type="button" value=" Calculate " onClick='operationForm(form);'> with <input type="button" value=" Calculate " onClick='operationForm();'>. Next change the function operationForm to accept no parameters. Then add id to your input answer box. Next for each if statement in the function use the elementById function to get the radios and the answerBox. For example, the first if should be
if (document.getElementById("addSelect").checked) {
answer = x + y;
document.getElementById("answerBox").value = answer;
}
This works:
JavaScript:
<script type="text/javascript">
function operationForm(){
var form = document.forms['operation_form'];
var x = form['numberOne'].value*1;
var y = form['numberTwo'].value*1;
var operation = null;
var answer = null;
if (form['addSelect'].checked == true) {
answer = x + y;
} else if (form['subtractSelect'].checked == true) {
answer = x - y;
} else if (form['multiplySelect'].checked == true) {
answer = x * y;
} else if (form['divideSelect'].checked == true) {
answer = x / y;
}
form['answerBox'].value = answer;
}
</script>
HTML:
<form name="operation_form">
<label>Enter two numbers, select an operation, and then click the button below.</label>
<br/>
<label>Number One:</label><input type="number" name='numberOne' />
<br/>
<br/>Number Two:</label><input type="number" name='numberTwo' />
<br/>
<input type="radio" name="operations" id="addSelect" value='' />Add
<input type="radio" name="operations" id="subtractSelect" value='' />Subtract
<input type="radio" name="operations" id="multiplySelect" value='' />Multiply
<input type="radio" name="operations" id="divideSelect" value='' />Divide
<br/>
<input type="button" value=" Calculate " onclick="operationForm();" />
<br/>
<label>Your answer is:</label><input type="text" name="answerBox">
</form>
Fixes between this and your example:
There are a ton of things wrong with the code you provided. I will update this answer shortly with as many as I can remember.
Update:
Please remember this is meant to be helpful and not punishing. So keep in mind that while listening to the attached feedback, I want you to learn this stuff.
Notes on your HTML:
1.) The biggest problem is none of the <label> elements have closing</label> tags.
Although, none of your html elements have any closing tags.
This will group all of the elements inside one big parent <label>.
So when the browser auto-closes the unclosed tags at the end of the document, this causes a hodgepodge of mixed up child elements. Close your elements.
2.) The first two text boxes have the same name="numbers" attribute. You can only do that with radio type inputs.
3.) Your <form> name="" attribute can NOT have the same name as the JavaScript function you are trying to call. They are stored in the same browser namespace so it causes an error.
Notes on your JavaScript:
1.) Your checked === true is an exact comparison. This will almost never evaluate to be truthful. Use checked == true, or better yet, just use if( my_element.checked ){}. Sometimes .checked will equal a string like this: .checked = 'checked'. So even though 'checked'==true it will never be truthful for 'checked'===true. The === means Exactly Equal. So only true===true.
2.) Your var x = document.opera.. ... .mberOne"); will store the whole <input> element into the x variable. You need to have ...mberOne").value; so just the value of the <input> is stored, not the whole html element.
3.) The only object that has a getElementById() method is the document. You can't use that from a document form object.
4.) You have to convert your x any y input values to numbers. If not, 5 + 5 will give you 55 instead of 10 because they are treated as strings. I multiplied them by * 1 to do that. I also changed the <input type='text' attribute to type='number' just to be safe.
5.) You can assign your answerBox.value just one time at the end of the function instead of doing it once per if(){} bracket. It will work the same but it's just much more readable.
6.) I used the syntax of form['numberOne'] instead of form.numberOne but they both work the same. It is referencing the element name (not necessarily the id) as it exists inside the form. <form> is the only object that lets you do this, whereas a <div> or <p> does not.

Count form inputs

I have this page (things which I need are at the bottom) and I need to count values from input (type numbers; it's quantity of product) and print value for each product (there are 4 products) and then all values together. Now I'm trying code for count value for each product. I have this Fiddle (code at the end of this post) code, but at my web it doesn't work. And question is why? And next question, after I will have values for each product, how can I pick them from and adding together?
HTML
<input type="number" value="10" class="number rowModre" min="0" name="pocetModre" id="pocetModre">
<div class="cena" id="cenaModre"></div>
JS
var string = $('#pocetModre').val();
$('#cenaModre').html(string);
Thank you very much.
Your question is not quite clear but i guess you are looking for something like this:
http://jsfiddle.net/akpn3/522/
var total = 0;
$(".number").each(function () {
$(".listprice").append("US $" + $(this).val() +"</br>");
total = total + parseInt($(this).val());
});
$(".listprice").append("Total : US $" + total);

Updated HTML from JavaScript variable

im trying to build a form with a few number type inputs that the users picks and one checkbox.
im not using php its all java cause im trying to count a bill using his inputs and print out the result.
how do i print those variables? document.write wont do cause its immidetly prints the var without the calculation.
here is some of the script (which is nothing):
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
var shutter_price
shutter_price = ($('#shutter').val())*200;
if (shutter != '0' )
write(shutter_price);
});
and the form's input:
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter">
any suggestions?
Instead of document.write it would be better to update or add an element on the page.
For example, modifying your provided code and markup:
Javascript (jQuery)
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
$('#shutter').on("change", function(e) {
var shutter_price = $(this).val()*200;
if (shutter_price >= 0) {
$('#shutter-result').text(shutter_price);
}
});
});
HTML
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter" min="0" step="1" pattern="\d+" />
<div id="shutter-result"></div>
JSFiddle
I think you can create a div on your HTML,
and use: $('#id_of_div_where_you_want_to_write').html("text you want to write");
p.s. This is javascript
javascript != java o/
Hope it helps bro!
i've typed the whole calculation.
i have a submmision button which by clicking needs to retrive the sum.
it doesnt work... im pretty new at javascript so i cant really tell where is the problem.
here is the code:
$('#home_price').submit(function(){
var shutter_price, lights_price, socket_price, screen10_price, screen7_price, dimmer_price, x
var total_price = 3000;
shutter_price = ($('#shutter').val())*200;
light_price = ($('#lights').val())*200;
socket_price = ($('#socket').val())*200;
screen10_price = ($('#screen10').val())*700;
screen7_price = ($('#screen7').val())*200;
dimmer_price = ($('#dimmer').val())*400;
if($('#boiler').is(":checked")==true){
total_price+=600;
x+=1;
}
x+=($('#shutter').val())*2+($('#lights').val())+($('#socket').val());
Math.floor(x);
x+=1;
total_price = total_price + shutter_price + light_price + socket_price + screen10_price + screen7_price + dimmer_price + x*400;
$('#home_pricing').val()=total_price;
if($('#home_pricing').val() < 6000)
alert('the solution invalid');
else
alert(" total: " + $('#home_pricing').val());
});
});
and a piece of the html code:
<label for="screen7"> 7inch screen </label>
<input style="margin-right:70px" name="screen7" type="number" id="screen7"> <br><br>
<label for="dimmer"> dimmer</label>
<input style="margin-right:174px" name="dimmer" type="number" id="dimmer"> <br><br>
<label for="boiler"> bolier </label>
<input style="margin-right:148px" type="checkbox" name="boiler" id="boiler" > <br><br>
<div>
<input type="submit" name=" home_pricing " id="home_pricing" value=" calculate " >
</div>
</form>
any suggestion of how to make the computation and retrive an alert window or other sort of window with the answer?
tnx
I know you did not say that you are using jquery, but I would highly recommenced it, because it makes javascript a lot easier. If you need to display this value to the user then you can use jquery's html function. Here is the link, https://api.jquery.com/html/. I would just write the value to a div that's is suppose to display the answer.
Let me know if you need it, and I can give you a quick plunker.

How do I execute a JavaScript function from clicking an HTML button?

I am trying to write a short piece of html code that, given two initial amounts, attempts to find the number greater than or equal to the first that wholly divides the second given amount. The code tries to divide the numbers, and if it is unsuccessful, adds 1 to the first number and tries to divide again, etc...
I want the code to return the value that does wholly divide the second number AND the answer to the division (with some plain text appearing around it).
Added to this, or at least I'd like there to be, is that upon clicking one of 5 different buttons a multiplication operation is performed on the first given number, it is rounded up to the nearest whole number, and THEN the function attempts to divide this into the second given number.
It's difficult to explain exactly what I want without showing you the code I have so far, so here it is:
<html>
<head>
<b>Rounded Commodity Pricing:</b><br>
<script language="Javascript">
function finddivid(marketprice,tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
if
(currency == "KWD")
var currencyMarketprice = Math.ceil(marketprice*KWDex)
else if
(currency == "GBP")
var currencyMarketprice = Math.ceil(marketprice*GBPex)
else if
(currency == "USD")
var currencyMarketprice = Math.ceil(marketprice*USDex)
else if
(currency == "CAD")
var currencyMarketprice = Math.ceil(marketprice*CADex)
else if
(currency == "EUR")
var currencyMarketprice = Math.ceil(marketprice*EURex)
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice +" " +currency +" per mt");
else
{for (var counter = currencyMarketprice+1; counter<(currencyMarketprice*2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter +" " +currency +" per mt");}}};
</script>
</head>
<p>Select currency:
<input type="button" value="KWD" OnClick="var currency = KWD">
<input type="button" value="USD" OnClick="var currency = USD">
<input type="button" value="GBP" OnClick="var currency = GBP">
<input type="button" value="EUR" OnClick="var currency = EUR">
<input type="button" value="CAD" OnClick="var currency = CAD">
<P>Enter today's price of commodity in USD: <input name="mktprc" input type="number"><br><p>
<P>Enter value of trade: <input name="trdval" input type="number">
<input type="button" value="Calculate" OnClick="showMeArea.value=finddivid(mktprc,trdval);">
<p>
<br><br>
<input name="showMeArea" readonly="true" size="30">
</html>
If you run this html in your browser you should see what I am trying to achieve.
It is far from complete but here are the main problems/features that I need help with:
I would like to be able to click on one of the 'currency' buttons so that upon clicking, the variable 'currency' is assigned and then used in the function finddivid.
(2. This isn't as important right now, but eventually, once this is working, I'd like it so that upon clicking one of the currency buttons, it changes colour, or is highlighted or something so that the user knows which currency rate they are using.)
Upon entering the numbers into the two boxes I would like to click 'Calculate' and have it return what I've written in the function into the 'showMeArea' read-only box at the end of the code.
I know I'm probably missing loads of stuff and I might be miles away from success but I am very new to programming (started 4 days ago!) so would like any like of help that can be offered.
Thanks in advance of your comments.
The first request requires that you put the currency into the actual script, and I would recommend using a setter function:
<script language="Javascript">
var currency; // you might want to set this at a default just in case
function setCurrency(val) { currency = val; } // Setter function
function finddivid(marketprice,tradevalue) {
Then call it in your button click:
<input type="button" value="KWD" onClick="setCurrency('KWD');">
As for the second request, I'd say you have the concept down well enough, but you don't have the method exactly right. First your inputs will need an id attribute:
<input name="mktprc" id="mktprc" input type="number">
<input name="trdval" id="trdval" input type="number">
The name attribute is used for posting values, the id attribute is used by javascript to find elements within a page. Using jQuery would make retrieving these elements easy, but I'll show both the jQuery and the standard JavaScript method of doing this:
jQuery:
<input type="button" value="Calculate" OnClick="$('#showMeArea').val(finddivid($('#mktprc'),$(#'trdval')));">
The $('#id') selects an element. The method .val() sets the value.
Note for the jQuery purists: Yes, there are much better/sophisticated ways to accomplish this with jQuery, but this answer is targeted to my perception of OP's JavaScript capability.
Standard Javascript:
<input type="button" value="Calculate" OnClick="document.getElementById('showMeArea').value = finddivid(document.getElementById('mktprc'),document.getElementById('trdval'));">

Categories

Resources