I'm making a basic usd converter for practice in html/javascript.
However when I select the euro option it does the same as for the peso option.
<html>
<head>
<title>Currency Converter</title>
<style>
</style>
</head>
<body>
<input id="amount"> </input>
<p>usd Contverted to</p>
<p class="output"> </p>
<select id="select"> <option value="1">Peso's</option> <option value="2">Euro's</option> </select>
<p id="answer"> is </p>
<input type="submit" value="Submit" onclick="run()">
<script>
function run() {
var Amount = document.getElementById("amount").value;
if (select = 1) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 16.39 + " =-=-=";
} else if (select = 2) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 0.9 + " =-=-=";
} else {
}
</script>
</body>
</html>
You are not comparing select,you are setting it.
if (select == 1) {
document.getElementById("answer").innerHTML = ...
} else if (select == 2) {
= -> setting a value
== -> comparing
it should be select == 1
select=1 will always return true, because this way you are simply assigning a value, not checking for equality
You are not getting value of select
You are not comparing select value in if condition, make it as select == 1 and select == 2
Complete solution here
Change your javaScript function as below
function run() {
var Amount=document.getElementById("amount").value;
var select=document.getElementById("select").value;
if (select == 1) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 16.39 + " =-=-=";
} else if (select == 2) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 0.9 + " =-=-=";
} else {
}
}
Related
I want to update the value of the counting variable after the words have been clicked, so they can be sorted from the highest clicked value from an array.
The variable value doesn't carry over to the next button.
I made the two variables as global variables in order to use it in other functions, but it doesn't seem to work and I also want the submit button to get updates after the user clicks the words after they have submitted once.
<h4> Communication </h4>
<button onclick="addressed()">addressed</button> ,
<button onclick="arbitrated()">arbitrated</button> ,
<br>-------------------
<p id="demo"> </p>
<p id="demo1"> </p>
<button onclick="myFunction()">Sort</button>
<p id="demo3"></p>
<script>
var countAddressed=0 ;
var countArbitrated=0;
var mostChosen = [
{word:"addressed:", selectedTimes:countAddressed},
{word:"arbitrated:", selectedTimes:countArbitrated}];
//set every buttons for action words
function addressed() {
countAddressed += 1;
//count how many individual action words there are.
document.getElementById("demo").innerHTML = "addressed: " + countAddressed;
}
function arbitrated() {
countArbitrated += 1;
//count how many individual action words there are.
document.getElementById("demo1").innerHTML ="arbitrated: " + countArbitrated;
}
function myFunction() {
mostChosen.sort(function(a, b){return b.selectedTimes - a. selectedTimes});
displayWords();
}
function displayWords() {
document.getElementById("demo3").innerHTML =
mostChosen[0].word + " " + mostChosen[0].selectedTimes + "<br>" + mostChosen[1].word + " " + mostChosen[1].selectedTimes + "<br>";
}
----I want this :
Communication
addressed(button) , arbitrated (button),
addressed: 3
arbitrated: 5
Sort(button)
addressed: 5
arbitrated: 3
----but I am getting this:
Communication
addressed , arbitrated ,
addressed: 3
arbitrated: 5
Sort
addressed: 0
arbitrated: 0
As I have mentioned in the comment, you are not updating mostChosen array when buttons are clicked.
// Update addressed count in addressed() function
mostChosen.forEach(token => {
if (token.word == 'addressed:') {
token.selectedTimes = countAddressed;
}
});
// Similar update is done in arbitrated() function
Here is the running code (your code, modified slightly) that modifies the array mostChosen:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Prescriptions</title>
</head>
<body>
<h4> Communication </h4>
<button onclick="addressed()">addressed</button> ,
<button onclick="arbitrated()">arbitrated</button> ,
<br>-------------------
<p id="demo"> </p>
<p id="demo1"> </p>
<button onclick="myFunction()">Sort</button>
<p id="demo3"></p>
<script>
var countAddressed = 0;
var countArbitrated = 0;
var mostChosen = [
{ word: "addressed:", selectedTimes: countAddressed },
{ word: "arbitrated:", selectedTimes: countArbitrated }];
//set every buttons for action words
function addressed() {
countAddressed += 1;
mostChosen.forEach(token => {
if (token.word == 'addressed:') {
token.selectedTimes = countAddressed;
}
});
//count how many individual action words there are.
document.getElementById("demo").innerHTML = "addressed: " + countAddressed;
}
function arbitrated() {
countArbitrated += 1;
mostChosen.forEach(token => {
if (token.word == 'arbitrated:') {
token.selectedTimes = countArbitrated;
}
});
//count how many individual action words there are.
document.getElementById("demo1").innerHTML = "arbitrated: " + countArbitrated;
}
function myFunction() {
mostChosen = mostChosen.sort(function (a, b) { return b.selectedTimes - a.selectedTimes });
displayWords();
}
function displayWords() {
document.getElementById("demo3").innerHTML =
mostChosen[0].word + " " + mostChosen[0].selectedTimes + "<br>" + mostChosen[1].word + " " + mostChosen[1].selectedTimes + "<br>";
}
</script>
</body>
I want to convert, with Select menu. So the first input box will read what temperature to convert from Select Menu, But it didn't work. When I select menu Celsius so the input will read the temperature as Celsius.
function myFunction() {
if (document.getElementById("temperature").value == "Celcius") {
convertc();
} else {
convertf();
}
}
function convertc() {
var x;
document.getElementById("demo").innerHTML = " Degree Celcius ";
x = (document.getElementById("c").value - 32) * 5 / 9;
document.getElementById("f").value = Math.round(x);
}
function convertf() {
var x;
document.getElementById("demo").innerHTML = " Degree Fahrenheit ";
x = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(x);
}
<h2>JavaScript Celcius to Fahrenhet</h2>
<form>
<select id="temperature" onchange="myFunction()">
<option value="Celcius">Celcius</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</form>
<p>
<input id="c"><span id="demo"> Degree </span></p>
<p>
<input id="f"></p>
You have multiple selector wrong in your Html as it has spaces on the ID's and in JavaScript selector you don't have space.
Just fix spaces in your elements ID's and it will work
e.g. "demo " != "demo"
Below is corrected ID's and JavaScript Selectors
function myFunction() {
if (document.getElementById("temperature").value == "Celcius") {
convertc();
} else {
convertf();
}
}
function convertc() {
var x;
document.getElementById("demo").innerHTML = " Degree Celcius ";
x = (document.getElementById("c").value - 32) * 5 / 9;
document.getElementById("f").value = Math.round(x);
}
function convertf() {
var x;
document.getElementById("demo").innerHTML = " Degree Fahrenheit ";
x = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(x);
}
<body>
<h2>JavaScript Celcius to Fahrenhet</h2>
<form>
<select id="temperature" onchange="myFunction()">
<option value="Celcius">Celcius</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</form>
<p>
<input id="c"><span id="demo"> Degree </span></p>
<p>
<input id="f" ></p>
</body>
If you want to automatically select the first select option, you will need to trigger the event.
Note: For the trigger functionality, I reused logic from a previous answer of mine.
I also converted the calculations to lambda constants for brevity, see below.
const FAHRENHEIT_TO_CELSIUS = (value) => (value - 32) * 5 / 9;
const CELSIUS_TO_FAHRENHEIT = (value) => value * 9 / 5 + 32;
// ==============================================================
var comboEl = document.getElementById('temperature');
addEventListener(comboEl, 'change', onComboChange); // Add an event listener.
triggerEvent(comboEl, 'change', {}); // Automatically trigger the event.
// ==============================================================
function onComboChange(e) {
var inputValue = document.getElementById('input-degrees').value;
if (e.target.value === 'Celsius') {
updateDisplay('Celsius', CELSIUS_TO_FAHRENHEIT(inputValue));
} else {
updateDisplay('Fahrenheit', FAHRENHEIT_TO_CELSIUS(inputValue));
}
}
function updateDisplay(label, value) {
document.getElementById('degrees-label').innerHTML = 'Degrees ' + label;
document.getElementById('output-degrees').value = Math.round(value);
}
// ==============================================================
function addEventListener(el, eventName, handler) {
if (el.addEventListener) {
el.addEventListener(eventName, handler);
} else {
el.attachEvent('on' + eventName, function() {
handler.call(el);
});
}
}
function triggerEvent(el, eventName, options) {
var event;
if (window.CustomEvent) {
event = new CustomEvent(eventName, options);
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent(eventName, true, true, options);
}
el.dispatchEvent(event);
}
<h2>JavaScript Celsius to Fahrenheit</h2>
<form>
<select id="temperature">
<option value="Celsius">Celcius</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</form>
<p>
<input id="input-degrees" value="0" />
<span id="degrees-label">Degrees</span>
</p>
<p><input id="output-degrees" /></p>
For an assignment, I need to make a JS number guessing game. It needs to include a loop to check the user's guess and a reset game button. My problem is getting the loop to work. I want the number of turns to start at 10. Each time the user makes an incorrect guess, their number of turns decreases by 1, and if they guess correctly, their number of turns is 0. If they push the "Start New Game" button, a new number should be generated and the number of turns should be reset to 10.
The loop doesn't specifically need to be a while loop, I just need one in the code for my assignment. Can anybody help me out?
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it?</p>
<!-- FORM (Includes button to confirm guess, input box, and output box) -->
<form id="Input" name="Input">
<input name="guess" placeholder="Insert your guess" type="number">
<input name="requestInfo" onclick="getResults()" type="button" value="Confirm">
<p></p>
<textarea cols="50" name="results" readonly="true" rows="8"></textarea>
<p></p><input name="newGame" onclick="resetGame()" type="button" value="Start New Game">
</form><!-- JAVASCRIPT START -->
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns = 10;
function checkNumber() {
var guess = parseFloat(document.Input.guess.value);
while (turns > 0) {
if (guess == num) {
turns = 0;
document.Input.results.value = "Congratulations, you won! The mystery number was " + num + ".";
} else if (guess < num) {
turns--;
document.Input.results.value = "Your guess was too low. Turns remaining: " + turns;
} else if (guess > num) {
turns--;
document.Input.results.value = "Your guess was too high. Turns remaining: " + turns;
}
}
}
function resetGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
document.Input.guess.value = "";
document.Input.results.value = "";
}
function getResults() {
checkNumber();
}
</script>
</body>
Alright, I guess since it is a college/HS assignment your professor is trying to teach you using prompt under a loop.
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it?</p>
<!-- FORM (Includes button to confirm guess, input box, and output box) -->
<form id="Input" name="Input">
<input name="requestInfo" onclick="getResults()" type="button" value="Start Guessing!">
<input name="newGame" onclick="resetGame()" type="button" value="Start New Game">
</form><!-- JAVASCRIPT START -->
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns = 10;
function checkNumber() {
while (turns > 0) {
guess=prompt("Tell me your guess.", "Your guess: ");
if (guess == num) {
turns = 0;
alert("Congratulations, you won! The mystery number was " + num + ".");
} else if (guess < num) {
turns--;
alert("Your guess was too low. Turns remaining: " + turns);
} else if (guess > num) {
turns--;
alert("Your guess was too high. Turns remaining: " + turns);
}
}
if (turns==0)
alert ("You failed to guess sadly.");
}
function resetGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
}
function getResults() {
checkNumber();
}
</script>
I agree that the taks seems a bit weird - obviously, with a non-modal dialog, you will not need a loop.
One thing you could do is use the prompt method (example: window.prompt("sometext","defaultText");), which would then open a modal dialog to ask the user until the number of remaining guesses is zero, or until the guess was correct. That would work within the loop.
Here have a go with this one. Makes sure that the user enters a number.
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it? Click button to start game.</p>
<button type="button" onclick="startNewGame()">Start New Game</button>
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns;
function checkNumber() {
while (turns > 0) {
var guess = prompt("Insert your guess");
if (!guess || isNaN(guess)) {
alert("Please enter a valid number");
continue;
}
if (guess == num) {
alert("Congratulations, you won! The mystery number was " + num + ".");
return;
} else {
turns--;
if (guess < num) {
alert("Your guess was too low. Turns remaining: " + turns);
} else if (guess > num) {
alert("Your guess was too high. Turns remaining: " + turns);
}
}
}
if (turns == 0) {
alert("You have lost");
}
}
function startNewGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
checkNumber();
}
</script>
</body>
I have created a conversion table which converts miles to kilometres and kilometres to miles depending on whichever one the user chooses. They input two numbers which indicates the two ranges so if they input 2 and 5 and choose km to m it will then show 2km to 5km converted to miles. However, what I am trying to do is if the user inputs a greater number to start with for instance if you enter 10 and 2 it should still do the same but rather it should go from 10km down to 2km so in descending order, so I know it will be something along the lines of if(rangeStart>rangeEnd){i--;}
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function conversion(n) {
if (document.getElementById('mtokm').checked) {
return (n/0.62137).toFixed(2);
}
else {
return (n*0.62137).toFixed(2);
}
}
function conversionTable(rangeStart, rangeEnd) {
if(atLeastOneRadio() && rangeStart != false && rangeEnd != false) {
divStr="<table border=1><tr><td>Miles</td><td>Kilometres</td></tr>";}
for(i=rangeStart;i<=rangeEnd;i++) {
if(i%2==0)
{
divStr+= "<tr bgcolor=\"yellow\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
else
{
divStr+= "<tr bgcolor=\"green\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
}
document.getElementById("divResult").innerHTML=divStr;
}
else
{
alert("Please make sure you have entered an integer in both text boxes");
}
}
function getnputValue(input) {
var nn = $("input[name=convert]:checked").val()
var myInt = document.getElementById(input).value;
if(myInt == parseInt(myInt))
return parseInt(myInt);
else
return false;
}
function check() {
var radios = document.getElementsByName("choice");
$("input[name=convert]:checked").val()
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
return true;
}
}
return false;
}
function atLeastOneRadio() {
return ($('input[type=radio]:checked').length > 0);
}
</script>
</head>
<body>
<p>
Start : <input type=textbox id=rangeTxt value=""/>
End : <input type=textbox id=rangeTxt2 value=""/>
<input type=radio name="convert" id="mtokm" value ="Miles to Kilometre"/> Miles to Kilometre
<input type=radio name="convert" id="kmtom" value ="Kilometre to Miles"/> Kilometre to Miles
<br>
<br>
<button onClick="conversionTable(getnputValue('rangeTxt'), getnputValue('rangeTxt2'))">Convert</button>
</p>
<div id="divResult">
</div>
</body>
</html>
Check whether the end is higher or lower than the start. Then set variables that are used to control the for loop.
var increment, compare;
if (rangeStart <= rangeEnd) {
increment = 1;
compare = function(x, y) {
return x <= y;
};
} else {
increment = -1;
compare = function(x, y) {
return x >= y;
};
}
for (i = rangeStart; compare(i, rangeEnd); i += increment) {
// display code
}
All this program should/needs to do is do simple conversions between US & Metric, however, for some reason it is resisting every effort I have made to make it work. From what I can tell my script is not firing, I have worked relentlessly to fix it but my lack of experience with JS has made it an uphill battle. My HTML and JS appear to be in good order, so it must be my understanding of what I've written that is failing me.
The values for calculation come straight from Google, so they should be solid.
function calc()
{
var h;
var ee = isNaN(document.getElementById("number")).value;
if (ee == "true")
{
document.writeln("Please use only numerical keys I.E 128");
}
else if (document.getElementById("us").value == 1)
{if (document.getElementById("met").value == 4)
{
h = (document.getElementById("number").value * 453.592;
document.writeln(document.getElementById("number").value + " pounds is" + h + "grams.");
}
else
document.writeln("This is not a valid conversion!")
}
else if (document.getElementById("us").value == 2)
{if (document.getElementById("met").value == 5)
{
h = (document.getElementById("number").value * 0.946353;
document.writeln(document.getElementById("number").value + " liters is" + h + "quarts.");
}
else
document.writeln("This is not a valid conversion!");
}
else if (document.getElementById("us").value == 3)
{if (document.getElementById("met").value == 6)
{
h = (document.getElementById("number").value * 2.54;
document.writeln(document.getElementById("number").value + " inches is" + h + "centimeters.");
}
else
document.writeln("This is not a valid conversion!");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>U.S. to Metric Converter</title>
<script type="text/javascript" src="conversion.js"></script>
</head>
<body>
<form>
<input type="text" id="number">
<select name="U.S." id="us">
<option value="1">Pound(s)</option>
<option value="2">Quart(s)</option>
<option value="3">Inch(es)</option>
</select>
to
<select name="Metric" id="met">
<option value="4">Gram(s)</option>
<option value="5">Liter(s)</option>
<option value="6">Centimeter(s)</option>
</select>
</form>
<button type="button" id="btn" onclick="calc()">Convert!</button>
<div id ="hello"></div>
</body>
</html>
Please be ruthless with me if I am being a complete idiot somewhere in here, my main priority is getting this working but a better understanding of where I am failing is definitely important.
If you look closely on this line:
h = (document.getElementById("number").value * 453.592;
There is an unnecessary (. Get rid of that in all places where you have this code and your code will work.
Working Code Snippet:
function calc()
{
var h;
var ee = isNaN(document.getElementById("number")).value;
if (ee == "true")
{
document.writeln("Please use only numerical keys I.E 128");
}
else if (document.getElementById("us").value == 1)
{if (document.getElementById("met").value == 4)
{
h = document.getElementById("number").value * 453.592;
document.writeln(document.getElementById("number").value + " pounds is" + h + "grams.");
}
else
document.writeln("This is not a valid conversion!")
}
else if (document.getElementById("us").value == 2)
{if (document.getElementById("met").value == 5)
{
h = document.getElementById("number").value * 0.946353;
document.writeln(document.getElementById("number").value + " liters is" + h + "quarts.");
}
else
document.writeln("This is not a valid conversion!");
}
else if (document.getElementById("us").value == 3)
{if (document.getElementById("met").value == 6)
{
h = document.getElementById("number").value * 2.54;
document.writeln(document.getElementById("number").value + " inches is" + h + "centimeters.");
}
else
document.writeln("This is not a valid conversion!");
}
}
<html lang="en">
<head>
<meta charset="utf-8" />
<title>U.S. to Metric Converter</title>
<script type="text/javascript" src="conversion.js"></script>
</head>
<body>
<form>
<input type="text" id="number">
<select name="U.S." id="us">
<option value="1">Pound(s)</option>
<option value="2">Quart(s)</option>
<option value="3">Inch(es)</option>
</select>
to
<select name="Metric" id="met">
<option value="4">Gram(s)</option>
<option value="5">Liter(s)</option>
<option value="6">Centimeter(s)</option>
</select>
</form>
<button type="button" id="btn" onclick="calc()">Convert!</button>
<div id ="hello"></div>
</body>
</html>
Your Javascript has errors. You are missing the right bracket from a few expressions, e.g.:
h = (document.getElementById("number").value * 453.592; <-- add ) before ;
I suguest you try using a Javascript debugger such as Firebug, Chrome or IE Dev Tools, etc.
Have fun!