Im having trouble with the following code.
Here is the html part
<form name="convert">
Choose which currency you would like to convert the Euro to:
<select id="conversionType">
<option value="polish">Polish Zloty</option>
<option value="ukraine">Ukraine Hryvnia</option>
</select>
</br>
</br>
<hr>
Amount:<input id="amount" type="text" />
<input id="convertButton" type="button" value="Convert->"/>
To:
<input id="answer" type="text" name="answer" readonly="readonly"/>
</form>
and here is the javascript code.
it has been changed and helped before but i cannot see why it is not working
window.onload = initPage;
var euro;
var convert;
function initPage()
{
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
}
function calcAnswer()
{
//alert(document.getElementById("conversionType").value);
var value1 = document.getElementById("amount").value1;
var conversionType = document.getElementById("conversionType").value1;
//alert(conversionType);
//if(var value = document.getElementById("conversionType").value=="polish");
// document.getElementById("answer").value=value1 * 4.4976;
//else
// document.getElementById("answer").value=value1* 10.43958;
if(conversionType == "polish") {
document.getElementById("answer").value1=value1 * 4.4976;
} else {
document.getElementById("answer").value1=value1 * 10.43958;
}
}
it will not work at all. i dont know why because i think that the theory is sound. any help wpuld be much appreciated
Any time you do this:
document.getElementById("amount").value1
should be this:
document.getElementById("amount").value
no such thing as value1.
Shouldn't this
<pre> document.getElementById("answer").value1 </pre>
be
document.getElementById("answer").value = value1 * 4.4976
Related
I need help with this code. I have looked at tons of related questions but none has helped so far. Please help. These are exactly what I need:
To auto-update "Amount(USD)" once the value of "Amount(NGN)" is changed. Preferably with Vanilla Js.
I would also like to pick the final value of "Amount(USD)" and store in a PHP session to use in other pages.
See my code below:
<?php $grandTotal=10; ?>
<script type="text/javascript">
function calculateTotal() {
var nairaRate = document.pricecalculator.nairaRateToday.value; //get NGN rate today from admin and assign to nairaRate
dollarValue = eval(document.pricecalculator.nairaInput.value * nairaRate); //multiply nairaInput by nairaRate to get dollarValue
document.getElementById('dollar').innerHTML = dollarValue; //pass dollarValue to dollar to show auto-calculation onscreen
}
</script>
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC)</legend>
<label>Amount (NGN)</label><input type="number" name="nairaInput" onchange="calculateTotal()" value="1" /> <br />
<label>Amount (USD):</label><span id="dollar">1</span> <br />
<input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>
I was able to solve the problem like this:
<?php $grandTotal=10; ?> // set PHP variable
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC)</legend>
<label>Amount (NGN)</label><input type="number" id="naira-input" name="naira-input" onchange="calculateTotl()" value="1"/> <br />
<label>Amount (USD):</label><span id="dollar">1</span> <br />
</form>
<script type="text/javascript">
function calculateTotl() {
var nairaRate = document.getElementById("naira-input").value;
// Select your current input
let phpval = "<?= $grandTotal ?>"; // grab php value
var dollarResult = document.querySelector('#dollar');
var total = Number(nairaRate) * Number(phpval); evaluate current input * php value
return dollarResult.innerHTML = total; // write result to #dollar
}
</script>
Try this (worked for me):
var ngn = document.getElementById('ngn');
var dollar = document.getElementById('dollar');
ngn.onchange = ()=>{dollar.innerText=ngn.value*0.0026}
Check the following code. I have used a hardcoded value, that is 7 as nairaRate
let nairaInput = document.querySelector("input[name='NairaValue']")
nairaInput.addEventListener('change', (e) => calculateTotal(e.target.value, 7))
function calculateTotal(input, nairaRate) {
var resultInDollar = document.querySelector('#dollar');
var total = Number(input) / Number(nairaRate);
return resultInDollar.innerHTML = total
}
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC) Naira At 7</legend>
<label>Amount (NGN)</label><input type="number" name="NairaValue" onchange="calculateTotal()" value="0" /> <br />
<label>Amount (USD):</label><span id="dollar">0</span> <br />
<input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>
Good Luck!
I'm new to JavaScript and I’m having issues trying to create a drop down list unit converter. The project calls for the code to convert miles to feet, Celsius to Fahrenheit and pounds to grams. The issue is when I enter the values the output is way off.
No matter what number I enter or unit I select I get the same result of 14514.944, instead of the appropriate (5280 feet, 33.8°, 453.592g, etc.). If I double click the submit button I get 62573043513.9154, triple click 269748534086686000, etc.
I know I’m missing something in the convert_unit function, but I’m not sure what. I’ve tried adding and removing various code and nothing is working.
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value)
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
<form>
<fieldset>
<label id="enter">Numeric Value</label>
<p>
<input type="number" placeholder="Enter Value" name=" " value=" " id="numInput" />
</p>
</fieldset>
<fieldset><label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onClick="convert_unit()";>Convert</button>
</fieldset>
<fieldset><label id="results">Results</label>
<p>
<input type="number" placeholder="Results" name="to_unit" id="numOutput" readonly /></p>
</fieldset>
</form>
Both of your variables are named numInput:
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
I'm guessing your second one should be numOutput. Also, there's no need to redefine these variables in JS unless you want to make it explicitly known what they are. HTML elements with IDs are already available in the global scope based on their ID name (with some caveats). In this case you could simply use numInput and numOutput throughout your program and it would still work even without these two lines.
i found 2 problems in your code.
The first is that in line 4 of the script, you overwrite the input of variable "numInput" with "numOutput" element. (Rename to 'numOutput')
The second problem is that, when script is loaded on page, the elements is not yet instanced. To solve that you can put the import tag right before </body> or add variables definition inside the function.
PS: Don't forget to use semicolons after every statement;
Jah Bless =)
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<fieldset>
<label id="enter">Pounds to Grams</label>
<p><input placeholder="Enter Value" name=" " value=" " id="numInput" type="number"></p>
</fieldset>
<fieldset>
<label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onclick="convert_unit()" ;="">Convert</button>
</fieldset>
<fieldset>
<label id="results">Pounds to Grams</label>
<p><input placeholder="Results" name="to_unit" id="numOutput" readonly="" type="number"></p>
</fieldset>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
function convert_unit() {
var numInput = document.getElementById('numInput');
var numOutput = document.getElementById('numOutput');
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
Your code corrected, customized and working perfectly!
var numInput = document.getElementById("numInput");
var numOutput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
if(numInput.value === "") {
if(confirm("No value inputed to convert! Consider default 1 unit?")) {
numInput.value = 1;
}
}
if(getSelectedUnitToConvert("conversion_type") == null) {
if(confirm("No conversion unit selected! Consider default Miles to Feet?")) {
document.getElementById("conversion_type").selectedIndex = 0;
}
}
if(getSelectedUnitToConvert("conversion_type") == "Miles to Feet") {
numOutput.value=numInput.value;
numOutput2.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("result1").innerHTML = "Miles";
document.getElementById("result2").innerHTML = "Feet";
} else if(getSelectedUnitToConvert("conversion_type") == "Celcius to Fahrenheit") {
numOutput.value=numInput.value;
numOutput2.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("result1").innerHTML = "Celcius";
document.getElementById("result2").innerHTML = "Fahrenheit";
} else if(getSelectedUnitToConvert("conversion_type") == "Pounds to Grams") {
numOutput.value=numInput.value;
numOutput2.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("result1").innerHTML = "Pounds";
document.getElementById("result2").innerHTML = "Grams";
}
}
function getSelectedUnitToConvert(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1) {
return null;
}
return elt.options[elt.selectedIndex].text;
}
div {
margin: 5px;
}
<form>
<fieldset>
<label id="enter">Value to Convert</label>
<p><input type="number" placeholder="Enter Value" value="" id="numInput" /></p>
</fieldset>
<fieldset><label>Units for Conversion</label>
<p><select id="conversion_type" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select></p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value="" onclick="convert_unit();">Convert</button>
</fieldset>
<fieldset><label id="results">Conversion Result:</label>
<p>
<div>
<input placeholder="Original Value" name="to_unit" id="numOutput" readonly />
<label id="result1"></label>
</div>
<div>
<input placeholder="Conversion Result" name="to_unit2" id="numOutput2" readonly />
<label id="result2"></label>
</div>
</p>
</fieldset>
</form>
I'm trying to use the information that I obtain through a form via a submit button, do a little processing, and print it out onto the web page, preventing it from being submitted to a web server by including (return false).
Here is the code to the page:
<html>
<head>
<title>SmithSellsStuff</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
var myData = {
price: "4.25",
taxRate: "0.07",
shipRate: "0.02"
};
myData.calculateTotal = function() {
myData.name = document.getElementById("name");
myData.date = document.getElementById("date");
myData.numItems = document.getElementById("number of items");
var itemTotal = myData.numItems * myData.price;
var taxTotal = (myData.numItems * myData.price) * myData.taxRate;
var shipTotal = (myData.numItems * myData.price) * myData.shipRate;
document.writeln(itemTotal);
document.writeln(taxTotal);
document.writeln(shipTotal);
};
</script>
<form>
</p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
</p>
<label>Number of items: <input type="number" name="number of items" id="number of items" tabindex="3"/></label>
</p>
<input type="submit" onclick="calculateTotal(); return false;"/>
</form>
</body>
</html>
On the first page, I have a simple form with a field for name, date, number of items total, and a submit button. One error I'm getting is in the onclick tag. It says '_kof_1' is defined but never used. I don't think it is allowing my calculateTotal function to call.
It's because the function was not declared in the global scope, but rather as a property of myData.
myData.calculateTotal = function() {
To solve this, simply change the call to:
<input type="submit" onclick="myData.calculateTotal(); return false;"/>
Furthermore, since you want to get the name, date, and number of items from the text fields, you have to get the .value property to get the contents of the input fields, like so:
myData.name = document.getElementById("name").value;
myData.date = document.getElementById("date").value;
myData.numItems = parseInt(document.getElementById("number of items").value);
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
function calculateTotal()
{
alert("hai");
var price="4.25";
var taxRate="0.07";
var shipRate="0.02";
var name = document.getElementById("name");
var date = document.getElementById("date");
var numItems = document.getElementById("number_of_items").value;
alert(numItems);
var itemTotal = numItems * price;
var taxTotal = (numItems * price) * taxRate;
var shipTotal = (numItems * price) * shipRate;
document.writeln("Total Items:"+itemTotal+"\tTax :"+taxTotal+"\tshipTotal:"+shipTotal);
}
</script>
<form>
<p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
<p>
<label>Number of items: <input type="number" name="number_of_items" id="number_of_items" tabindex="10"/></label>
</p>
<input type="submit" onclick="calculateTotal()"/>
</form>
</body>
</html>
alert is just for to know method is calling or not, Hope this will help you
I'm trying to collect data via forms on one page, then transfer that data to the next page for use in a JS function.
(Specifically, I want the user to input values for A, B, and C of the Quadratic equation, and then send to a page where a script takes those values and runs the equation + outputs an answer).
Here the code for my first page --->
<body>
<h1> Welcome to the Math Equation Solver </h1>
<p> Which equation would you like to solve? (Simply input the data for the equation you wish to solve). </p>
<form name="quad" method="get" action="JS_B.html">
<input
<input type="text" name="a_val" size="5">
<br>
<input type="text" name="b_val" size="5">
<br>
<input type="text" name="c_val" size="5">
<br>
<input type="submit" method="get" action="JS_B.html" value="Submit">
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
</form>
Here is the code for my second page --->
<title>JS_Math Scripts</title>
<body>
<script type="Javascript">
function answer()
{
var a = a_val
document.writeln(a_val)
var b = b_val
var c = c_val
var root = Math.pow(b, 2) - 4 * a * c
var answer1 = (-b + Math.sqrt(root)) / 2*a
var answer2 = (-b - Math.sqrt(root)) / 2*a
if(root<'0');
{
alert('This equation has no real solution.')
}else{
if(root=='0')
{
answerOne = answer1
document.writeln(answerOne)
answerTwo = 'No Second Answer'
}else{
answerOne = answer1
document.writeln(answerOne)
answerTwo = answer2
document.writeln(answerTwo)
}
}
}
// End -->
</script>
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
<input type="hidden" name="answerOne">
<input type="hidden" name="answerTwo">
<input type="hidden" name="Answer">
</body>
</html>
So anyways, when I input values for A, B, and C it takes me to the second page, but I'm not getting a result. I've tried inspect element and the console isn't indicating any errors, so I think my data is transferring correctly. Any ideas?
You can use FormData() to retrieve values from <input> elements within <form>; use JSON.stringify(), encodeURIComponent() to pass values from form to JS_B.html as query string.
At window load event at JS_B.html, use decodeURIComponent(), JSON.parse() to retrieve object at location.search; destructuring assignment to set variables within answer function using passed object.
Include ; following variable assignments, remove ; following if condition
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Welcome to the Math Equation Solver </h1>
<p> Which equation would you like to solve? (Simply input the data for the equation you wish to solve). </p>
<form name="quad">
<input type="text" name="a_val" size="5">
<br>
<input type="text" name="b_val" size="5">
<br>
<input type="text" name="c_val" size="5">
<br>
<input type="submit" value="Submit">
<!--
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
-->
</form>
<script>
var form = document.querySelector("form");
form.onsubmit = function(e) {
e.preventDefault();
var data = new FormData(this);
var obj = {};
for (prop of data.entries()) {
obj[prop[0]] = prop[1]
};
var query = encodeURIComponent(JSON.stringify(obj));
location.href = "JS_B.html?" + query;
}
</script>
</body>
</html>
JS_B.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function answer(obj) {
var {
a_val: a,
b_val: b,
c_val: c
} = obj;
document.writeln(a);
var root = Math.pow(b, 2) - 4 * a * c;
var answer1 = (-b + Math.sqrt(root)) / 2 * a;
var answer2 = (-b - Math.sqrt(root)) / 2 * a;
if (root < 0) {
alert('This equation has no real solution.')
} else {
if (root == 0) {
answerOne = answer1;
document.writeln(answerOne);
answerTwo = 'No Second Answer'
} else {
answerOne = answer1;
document.writeln(answerOne);
answerTwo = answer2;
document.writeln(answerTwo)
}
}
} // End -->
window.onload = function() {
var obj = JSON.parse(decodeURIComponent(location.search.slice(1)));
console.log(obj);
answer(obj);
}
</script>
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
<input type="hidden" name="answerOne">
<input type="hidden" name="answerTwo">
<input type="hidden" name="Answer">
</body>
</html>
plnkr http://plnkr.co/edit/aaY5rcJ6v0g7bdEEr7h0?p=preview
I'm currently trying to create a form that will extend on click using the method shown from this site. http://www.quirksmode.org/dom/domform.html
I have the Extending of the form more or less working fine, My issue is getting the Date field to correctly step up from the date that the user inputs in the first field.
Right now if I click on Add another Date, it adds a day to 1970-01-01 which i'm assuming is a default start date somewhere.
I'm not familiar enough with javascript to reference the generated date to the date that is initially selected by the User.
Here is a fiddle link of you want to see what I mean. https://jsfiddle.net/2nvz6kqj/9/
Note i'm pretty sure you can only get the date field to show up in Chrome correctly.
And here is my code.
<script type="text/javascript">
var counter = 0;
function moreFields() {
var date = document.getElementById("myDate").value;
counter++;
var newFields = document.getElementById("readroot").cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name;
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById("writeroot");
insertHere.parentNode.insertBefore(newFields,insertHere);
document.getElementById("myDate").stepUp(1);
}
window.onload = moreFields;
</script>
<body>
<div id="readroot" style="display: none">
<input type="button" value="Remove Date"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<input type="date" id="myDate" value="">
<select name="rankingsel">
<option>School Day</option>
<option value="day1">Day 1</option>
<option value="day2">Day 2</option>
<option value="day3">Day 3</option>
<option value="day4">Day 4</option>
<option value="day5">Day 5</option>
<option value="closed">School Closed</option>
</select><br /><br />
</div>
<form method="post" action="/cgi-bin/show_params.cgi">
<span id="writeroot"></span>
<input type="button" onclick="moreFields()" value="Add Another Date" />
<input type="submit" value="Send form" />
</form>
</body>
Ultimately once i get this working correctly, I'll submit it to a DB with PHP.
Ok, I changed a few things, but this should work for you.
NOTE: In order to keep the code and markup close to what you had, I didn't "fix" some of the JavaScript and HTML that I consider to be bad practice.
I also took some liberties with the readroot element IDs and writeroot is now a DIV not a SPAN as you had it.
<html>
<head>
<script type="text/javascript">
var counter = 0;
var date = new Date();
// this function adds a day to the date variable
function addDay (dateObj) {
var ticks = dateObj.getTime();
var newTicks = ticks + (24 * 60 * 60 * 1000);
dateObj.setTime(newTicks);
}
function moreFields() {
//var dateVal = document.getElementById("myDate").value;
counter++;
// querySelector is nicer way to get your elements
var newFields = document.querySelector("#readroot").cloneNode(true);
newFields.id = newFields.id + counter;
newFields.style = null;
// nifty way to convert node list into an array
var fields = Array.prototype.slice.call(newFields.childNodes);
// now use forEach instead of old-style for loop
fields.forEach(function (f,i,nodes) {
var theName = f.name;
if (theName) {
f.id = theName + counter;
}
});
// convert "writeroot" to div and just append the newFields container
var form = document.querySelector('#writeroot');
form.appendChild(newFields);
// to set the date, you need to use an ISO-format date string
var dateFields = form.querySelectorAll('[name="myDate"]');
var len = dateFields.length;
var dateField = dateFields[len - 1];
if (dateField) {
var dateISO = date.toISOString().substr(0,10);
dateField.value = dateISO;
addDay(date);
}
}
window.onload = moreFields;
</script>
</head>
<body>
<div id="readroot" style="display: none">
<input type="button" value="Remove Date"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<input type="date" name="myDate">
<select name="rankingsel">
<option>School Day</option>
<option value="day1">Day 1</option>
<option value="day2">Day 2</option>
<option value="day3">Day 3</option>
<option value="day4">Day 4</option>
<option value="day5">Day 5</option>
<option value="closed">School Closed</option>
</select><br /><br />
</div>
<form method="post" action="/cgi-bin/show_params.cgi">
<div id="writeroot"></div>
<input type="button" onclick="moreFields()" value="Add Another Date" />
<input type="submit" value="Send form" />
</form>
</body>
</html>