this code does not work, at least not complete way it should. I'm trying to run it so an item is selected and then deposit amounts are chosen on the select menu until the proper amount is equaled or exceeded, resulting in change, but I cant seem to get my if statements to work properly. If anyone sees the problem, I would much appreciate the help.
http://jsfiddle.net/YgX4z/
<script type="text/javascript">
var select;
function changedepositedInput(objDropDown) {
//console.log(parseFloat(objDropDown));
var objdeposited = document.getElementById("deposited");
objdeposited.value=parseFloat(objdeposited.value||'0');
var total=parseInt(objdeposited.value||'0');
objdeposited.value = parseFloat(objDropDown.value||'0')+total;
var cost=parseInt('0');
var water = document.getElementById("water");
var soda = document.getElementById("soda");
var coffee = document.getElementById("coffee");
var beer = document.getElementById("beer");
if (water.checked) {cost=parseInt('75');}
if (soda.checked) {cost=parseInt('150');}
if (coffee.checked) {cost=parseInt('100');}
if (beer.checked) {cost=parseInt('200');}
if (total>cost) {
var change=document.getElementById("change");
change.value=total-cost;
}
else {
var change=document.geElementById("change");
change.value="0";
}
if (total>=cost) {
var objdelivered=document.getElementById("delivered");
objdelivered.value="Yes";
}
else {
var objdelivered=document.getElementById("delivered");
objdelivered.value="No";
}
}
</script>
<h1>Vending Machine Project</h1>
<form name="vendingmachine" action=" ">
Choose Bevrage<br>
<input name="item" type="radio" id="water" checked="checked">Water 75 cents<br>
<input name="item" type="radio" id="soda">Soda $1.50<br>
<input name="item" type="radio" id="coffee">Coffee $1.00<br>
<input name="item" type="radio" id="beer">Beer $2.00<br>
<p>
<label>Deposit Money:
<select name="money" id="money" onchange="changedepositedInput(this)">
<option value="0">Choose Amount</option>
<option value="10">10 cents</option>
<option value="25">25 cents</option>
<option value="50">50 cents</option>
<option value="75">75 cents</option>
<option value="100">$1.00</option>
</select>
</label>
</p>
<p>Total Deposited:<input name="deposited" id="deposited" type="text" readonly="TRUE" value=""></p>
<p>Change Returned:<input name="change" id="change" type="text" readonly="TRUE" value=" "></p>
<p>Bevrage Delivered:<input name="delivered" id="delivered" type="text" readonly="TRUE" value=" "></p>
<p><input type="reset" value="Start Over"></p>
You have a typo here:
var change=document.geElementById("change");
Should be
var change=document.getElementById("change");
If you test in your fiddle, please don't use function changedepositedInput() as it won't evaluate properly. Instead define your function like this:
changedepositedInput=function(){
};
(Note the semicolon in the end)
Hint
You can use a modern browser's error/javascript console (or developer tools, as its oftentimes called) for debugging.
If you open that console and run your original fiddle, you'd get this error:
[Error] ReferenceError: Can't find variable: changedepositedInput
onchange (_display, line 75)
Once the function definition is changed (as mentioned before in my question), the actual problem shows up:
[Error] TypeError: 'undefined' is not a function (evaluating 'document.geElementById("change")')
changedepositedInput (_display, line 46)
onchange (_display, line 74)
Which points you straight at the typo.
See a working fiddle here
Related
I am using a plugin for my crowdfunding plateform which is working fine and is helping me a lot as I am not quite confortable with coding yet.
However I'd like to tweak a JavaScript function. When a customer chooses how much he wants to contribute, the customer can either decide the amount or the reward level he wants
Here is basically how the form is made:
<form action="" method="POST">
<div class="form-row inline left twothird">
<label for="level_select">Contribution Level
<span class="dropdown ">
<select name="level_select" class="dropdown__select">
<option value="1" data-price="5.00">Reward 1</option>
<option value="1" data-price="15.00">Reward 2</option>
<option value="1" data-price="25.00">Reward 3</option>
</span>
</label>
</div>
<div class="form-row inline third total">
<label for="total">Total</label>
<input type="text" class="total" name="total" id="total" value="">
</div>
<div class="form-row submit">
<input type="submit">
</div>
From there I want to bind levels with the amount entered by the user.
Currently, it is partially working as changing the amount depending on the selected level is pretty easy. Where I'm stuck is with changing the selected option depending on the input.
In the plugin I found the following lines which seems to be what I'm interested in:
jQuery(document).bind('price_change', function(event, price) {
jQuery('input[name="total"]').val(price);
var levelIndex = jQuery('select[name="level_select"]').prop('selectedIndex');
var levelPrice = jQuery('select[name="level_select"] option').eq(levelIndex).data('price');
if (price < levelPrice) {
jQuery('input[name="total"]').val(levelPrice);
}
});
Based on this I started to tweak it a bit but with my fairly low knowledge of jQuery here is where I am at the moment:
jQuery(document).ready(function() {
jQuery(document).bind('price_change', function(event, price) {
var price = jQuery('input.total').val();
var levelIndex = jQuery('select[name="level_select"]').prop('selectedIndex');
var levelPrice = jQuery('select[name="level_select"] option').eq(levelIndex).data('price');
var nextLevel = jQuery('select[name="level_select"] option').eq(levelIndex + 1);//got to check if exist, else NULL
if (nextLevel){var nextLevelPrice = jQuery('select[name="level_select"] option').eq(levelIndex + 1).data('price');}
var prevLevel = jQuery('select[name="level_select"] option').eq(levelIndex - 1);//got to check if exist, else NULL
if (prevLevel){var prevLevelPrice = jQuery('select[name="level_select"] option').eq(levelIndex - 1).data('price');}
while (prevLevel!=NULL && price < levelPrice) {
jQuery('input[name="total"]').val(prevLevel);
}
while (nextLevel != NULL && price < nextLevelPrice){
jQuery('input[name="total"]').val(nextLevel);
}
});
Am I on the right track or is their an easier way to proceed?
Thank you for your attention, any advice appreciated
This consists of two problems. The first problem is rounding numbers to a certain decimal point. The second problem is connecting the drop down menu to the right decimal.
First my code:
<style>
span{font-style:italic;}
span{color:green;}
</style>
<script>
function calcul(){
var sales = parseFloat(document.getElementById("sales").value);
var OpExp = parseFloat(document.getElementById("OpExp").value);
var TaxAll = parseFloat(document.getElementById("TaxAll").value);
var Depre = parseFloat(document.getElementById("Depre").value);
var Divid = parseFloat(document.getElementById("Divid").value);
var TaxR = parseFloat(document.getElementById("TaxR").value);
//GP = Gross Profit
var GP = sales - OpExp;
//TaxInc = Taxable Income
var TaxInc = GP + TaxAll;
//NetInc = Net Income
var NetInc = TaxInc - ((TaxR / 100) * TaxInc);
document.getElementById("NetIncome").innerHTML=
TaxInc - ((TaxR / 100) * TaxInc);
//AtRE = Addition to Retained Earnings
document.getElementById("AtRE").innerHTML = NetInc - Divid;
}
</script>
<form action="" id="nothing">
In 2007 the British building firm Balfour Betty plc had sales of
<input type="text" id="sales" maxlength="6" size="6">
million, total operating expenses of
<input type="text" id="OpExp" maxlength="6" size="6">
million, a tax allowance (rebate) of
<input type="text" id="TaxAll" maxlength="6" size="6">
million because of past losses, and
<input type="text" id="Depre" maxlength="6" size="6">
depreciation. <strong>What is the net income of the
firm?</strong><br />
<br />
Balfour Betty plc paid out <input type="text" id="Divid" maxlength="6" size="6"> million
in cash dividends. <strong>What is the addition to retained earnings?</strong><br />
<br />
The tax rate is <input type="text" id="TaxR" maxlength="6" size="6"> %.<br />
<br />
<input type="button" value="Calculate" id="but" onclick="calcul()" /><br />
<br />
</form>
<strong>The Net Income of Balfour Betty plc is </strong><span id="NetIncome">XXX</span>
<strong> million</strong><br />
<br />
<strong>The addition to retained earnings of Balfour Betty plc is </strong><span id="AtRE">
XXX</span><strong> million</strong>
<br />
<br />
The first problem: rounding numbers. The following answer: <span id="NetIncome"> needs to be rounded dynamically. I've tried to add a new variable called RNetInc and add the following equation RNetInc = NetInc.toFixed(4), but it only gave me two decimals, and after a refresh it doesn't even work anymore. What is the best way to round the answer to N decimals?
The second problem is one I don't know if it's possible. What I have in mind is the following:
A dropdown menu
<select>
<option value"1">1 decimal</option>
<option value"2">2 decimals</option>
<option value"3">3 decimals</option>
</select>
So, what I want is that when I click N decimal, the answer will change to N decimal. This is a very complex situation, but one I often need.
Since I only know the (very) basics of Javascript, even using Google I cannot find the answer. Can someone get me on the right track (if it's even possible)? Thanks in advance.
I'd suggest to fix only the final results, toFixed() returns a string.
HTML for select:
<select id="dec">
<option value="1">1 decimal</option>
<option value="2">2 decimals</option>
<option value="3">3 decimals</option>
</select>
In calcul():
var decs = +(document.getElementById('dec').value); // Add this line
document.getElementById("NetIncome").innerHTML = (TaxInc - ((TaxR / 100) * TaxInc)).toFixed(decs);
document.getElementById("AtRE").innerHTML = (NetInc - Divid).toFixed(decs);
A live demo at jsFiddle (updated).
EDIT
Looks like I've partially missunderstood your question. Please check the updated fiddle, now you can also change the amount of decimals at any time by picking a value from select.
I am very new on HTML. I just trying to accept form value and want to show this value
in Alert. I try following code but it didn't help me...
I know this is very easy question but i am newbie on HTML,JavaScript. I search but didn't find relative to my requirement....
Javascript function....
function updateTxt(field1,field2)
{
var field1 = document.getElementById(field1);
var field2 = document.getElementById(field2);
alert(field1,field2);
}
HTML form
<input name="textfield" type="text" id="textfield" value="Search by keyword" class="search_input" >
<select name="select" id="select" class="input_list" >
<option>Search jobs by category</option>
<option>Business Sales Leadership Development Program</option>
<option>Business Sales Solutions</option>
<option>CTO</option>
<option>Call Center</option></select>
<input name="button" type="button" class="btn" value="Go" onClick="updateTxt(select,textfield)">
Please give me hint or direct me where i wrong...
Thanks in Advance
change this code
<input name="button" type="button" class="btn" value="Go" onclick="updateTxt()">
and also this
function updateTxt()
{
var field1 = document.getElementById('textfield').value;
var field2 = document.getElementById('select').options[document.getElementById('select').selectedIndex].value;
alert(field1+'&'+field2);
}
You need to pass strings into the updateTxt function. And alert can only take one parameter, so you'll have to concatenate the values of the fields, not the fields themselves. Your code would look like this:
JS:
function updateTxt(field1,field2)
{
var field1 = document.getElementById(field1).value;
var field2 = document.getElementById(field2).value;
alert(field1 + '\n' + field2);
}
HTML:
<input name="textfield" type="text" id="textfield" value="Search by keyword" class="search_input" >
<select name="select" id="select" class="input_list" onkeyup="updateTxt('select','txt2');">
<option>Search jobs by category</option>
<option>Business Sales Leadership Development Program</option>
<option>Business Sales Solutions</option>
<option>CTO</option>
<option>Call Center</option></select>
<input name="button" type="button" class="btn" value="Go" onClick="updateTxt('select', 'textfield')">
Demo
You will need to change the onClick to:
onclick="updateTxt('select','textfield');
because when you are using reserved words in JS it is not good - to say the least ;)
For full list of reseved words: http://www.javascripter.net/faq/reserved.htm
You can see there 'select'.
Btw, you might want to change the names to something better and avoid 'onClick' and JS inside your html.
Good luck.
Your code does not have an element with the id 'txt2'. Also try to use more explicit IDs, like 'myTextField' instead of 'select', it will make it easier to read and maintain your code.
Other than that, Amaan's answer should work.
this works perfectly as I want it to in Firefox, but it does not work in Chrome. Can anyone point me in the right direction please?
<g:javascript>
function selectedStatus()
{
var index = j("#statusId");
if(${statusValue} = ${Status.getAllEnums()})
{
index.selectedIndex = ${statusValue};
}
}
</g:javascript>
I am passing a value for a users status from a controller to a gsp page. I check to see if the value is equal to one of the values in the grails select, and if it is then I set this "current" value as the value appearing in the select box.
Here is my gsp...
<g:formRemote name="custom_status" url="[controller: 'traffic', action: 'status']">
<h4>
<g:select id="statusId" name="MyStatus" from="${Status.getAllEnums()}" value="${statusValue}" noSelection="['':'Please Select...']" onload="selectedStatus()" onchange="document.getElementById('sub_status').value = ''"/>
</h4>
<g:textField name="sub_status" value="${subStatusValue}" />
<g:submitButton name="submit_status" value="Apply Status" />
</g:formRemote>
The select box changes as desired in Firefox but no change occurs in Chrome.
Here is the resulting HTML...
<form onsubmit="jQuery.ajax({type:'POST',data:jQuery(this).serialize(), url:'/portal/traffic/status',success:function(data,textStatus){},error:function(XMLHttpRequest,textStatus,errorThrown){}});return false" method="post" action="/portal/traffic/status" id="custom_status">
<h4>
<select name="status" id="statusId" onload="selectedStatus()" onchange="document.getElementById('sub_status').value = ''" >
<option value="">Please Select...</option>
<option value="available" >available</option>
<option value="away" >away</option>
<option value="dnd" >dnd</option>
<option value="unavailable" >unavailable</option>
</select>
</h4>
<input type="text" name="sub_status" value="In a meeting" id="sub_status" />
<input type="submit" name="submit_status" value="Apply Status" id="submit_status" />
</form>
<br/>
Thanks
It's really strange why value="${statusValue}" doesn't work here. Btw, your Javascript code maybe invalid (i'm not sure what you have as a result JS, but it's very likely), so try following:
<g:javascript>
j(document).ready(function ()
{
j("#statusId").val('${statusValue}'); //I guess `j` is your prefix for jQuery, right?
});
</g:javascript>
and remove onload="selectedStatus()"
I have a Javascript calculator in which users can enter quantities of products/features, and it will multiply the quantity by the set price. Then, the result shows in a textbox below. My 2 questions are:
I can use <select> options and specify a value for each one like this:
<select name="SITE_EM_4.99" onChange="CalculateTotal(this.form)">
<option value=""> - Select - </option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
However, it won't let me do the same with checkboxes/radio buttons. How can I do that?
Two: Can I change the script so the total shows as actual text, vs in a text field? THANKS!
P.S. The script can be found HERE.
You can do it almost identically with radio buttons
<input type="radio" name="group1" value="Milk" onClick="CalculateTotal(this.form)" > Milk<br>
<input type="radio" name="group1" value="Butter" onClick="CalculateTotal(this.form)" > Butter<br>
Second question, very easy to do.
Put an empty div tag with an id where you want to show the results. t
Then just insert the values into the div tag as text using javascript below after finishing calculations.
var output= document.getElementById("outputDiv")
output.innerText = {value of CalculateTotal()}
EDIT: Requested Example
<script>
function CalculateTotal(myForm)
{
//do your calculations here
//...
//...
var text = //put whatev here that will be the output
var output= document.getElementById("outputDiv")
output.innerText = text;
}
</script>
<body>
<input type="radio" name="group1" value="1" onClick="CalculateTotal(this.form)" > Yes<br>
<input type="radio" name="group1" value="2" onClick="CalculateTotal(this.form)" > No<br>
<div id="outputDiv"></div>
instead of having an input for the total just switch to a span (or something else) with an id (let's say "total"), and just replace it with innerHTML
<script>
function CalculateTotal(frm) {
...
document.getElementById('total').innerHTML = round_decimals(order_total, 2);
...
}
</script>
<input type="checkbox" name="SITE_EM_4.99" value="1" onClick="CalculateTotal(this.form)">
<script>
document.write("Welcome to my world!!!");
</script>
This function can be used to print text within the document itself instead of in a text field.