JavaScript Unit Converter with 2 dropdown menus - javascript

I'm new to JavaScript. Trying to build, for practice, a simple unit converter kind of like the one that google uses for converting kilos to pounds, inches to meters, etc.
I'd like to have an input box for entering the number value.
After that, two lists in the HTML files so i can choose in first the unit i convert from; and on the second the unit i convert to.
Maybe is an obvious one but i have not been able to find an answer to this problem. I'll post the last code/approach i tried.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="simpleweightconversortest.js"></script>
</head>
<body>
<form>
<!-- Select 1-->
<label>From:</label>
<select name="converts" id="Selection">
<option>Chose Option</option>
<option value="kilograms1">Kilograms</option>
<option value="grams1">Grams</option>
<option value="miligrams1">Miligrams</option>
</select>
<!-- Select 2-->
<label>To:</label>
<select name="converts2" id="Selection2">
<option>Chose Option</option>
<option value="kilograms2">Kilograms</option>
<option value="grams2">Grams</option>
<option value="miligrams2">Miligrams</option>
</select>
<!--INPUT-->
<br>
<br>
<br>Value
<input type="number" id="value" placeholder="Insert value">
<!--RESULT -->
<br>Conversion
<input type="text" id="convertedOuput">
<br>
<br>
<input type="Button" onclick="Conversion()"
value="convert">
</form>
</body>
</html>
var val = document.getElementById("value").value;
var convertedOuput =document.getElementById("convertedOuput");
var selectFrom = document.getElementById("Selection");
var selectTo = document.getElementById("Selection2");
var madeSelection_1 = selecFrom[selectFrom.selectedIndex].value;
var madeSelection_2 = selectTo[selectTo.selectedIndex].value;
function Conversion() {
if (madeSelection_1 == "kilograms1" && madeSelection_2 == "kilograms2") {
var result = val * 1;
document.getElementById('convertedOuput').innerHTML = result;
}
}
I'm not getting any output in my "conversion" input box.
What am i doing wrong ? (i'm sure almost everything) Please help.

document.getElementById('convertedOuput').value = result should display the result of your function.

You have a typo:
var madeSelection_1 = selecFrom[selectFrom.selectedIndex].value;
This should be selectFrom and not selecFrom.
Also, you need to set the value of the input field using convertedOuput.value = result instead of setting its innerHTML. (By the way, convertedOuput is also misspelled, should be convertedOutput, but it's consistent, so it should work anyway.)
And finally, you are checking the selected units outside of the conversion button click handler, so they won't be updated when the user changes the selections in the dropdown. Move the corresponding lines which set value, convertedOuput and madeSelection_1 and madeSelection_2 into the Conversion function. (Explanation: Right now, the code is run once upon page load, so the values loaded there will always be the an empty string coming from the Choose option option. Afterwards, this part is run every time the button is clicked, so the values will be up to date.)
It works now:
function Conversion() {
var val = document.getElementById("value").value;
var convertedOutput = document.getElementById("convertedOutput");
var selectFrom = document.getElementById("Selection");
var selectTo = document.getElementById("Selection2");
var madeSelection_1 = selectFrom[selectFrom.selectedIndex].value;
var madeSelection_2 = selectTo[selectTo.selectedIndex].value;
if (madeSelection_1 == "kilograms1" && madeSelection_2 == "kilograms2") {
var result = val * 1;
convertedOutput.value = result;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="simpleweightconversortest.js"></script>
</head>
<body>
<form>
<!-- Select 1-->
<label>From:</label>
<select name="converts" id="Selection">
<option>Chose Option</option>
<option value="kilograms1">Kilograms</option>
<option value="grams1">Grams</option>
<option value="miligrams1">Miligrams</option>
</select>
<!-- Select 2-->
<label>To:</label>
<select name="converts2" id="Selection2">
<option>Chose Option</option>
<option value="kilograms2">Kilograms</option>
<option value="grams2">Grams</option>
<option value="miligrams2">Miligrams</option>
</select>
<!--INPUT-->
<br>
<br>
<br>Value
<input type="number" id="value" placeholder="Insert value">
<!--RESULT -->
<br>Conversion
<input type="text" id="convertedOutput">
<br>
<br>
<input type="Button" onclick="Conversion()" value="convert">
</form>
</body>
</html>
Note that you would have found a hint to these things more easily if you had looked into your browser's devtools - there you'd have seen an error about selecFrom.
Try pressing F12 in your browser. :-)
Furthermore, in the devtools you can do many powerful things to debug and analyze your code, such as executing arbitrary code at runtime, inspect variables, single-step through your lines of code, etc.
I'd recommend you to watch the Google Chrome Devtools Crash Course video on YouTube to get started!

Related

Using Javascript with HTML to get a selected option and display a String based on value

Sorry if this has been asked before, I've looked around (this site and a couple others) for examples and snippets of code but nothing seems to work.
I'm taking a course in HTML, an assignment requires using a script to check a ddl and display a line of text based on the selected option. The problem is that what I've found online seems a bit different to the example our teacher provided (we're using Dreamweaver 2015 if that makes a difference.)
Here's what I'm stuck with after a couple hours of cannibalizing code from a few different threads.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Hot Buns </title>
</head>
<script type="text/javascript">
function showDetails()
{
var x= document.getElementById("slctOrder");
var val= x.options[x.selectedIndex].text;
<!-- DW only displays item(n) and len after the dot, I typed in "text" manually -->
document.forms["frmOrder"]["Details"].value = val;
<!-- I'm just trying to have it display anything at this point,
same as above, I typed "value" since DW doesn't seem to recognize this code
(this is from the teacher's example) -->
}
</script>
<body>
<p> <h2> Welcome to Hot Buns </h2> <br> <h3> Ham can we bee'f service? </h3></p>
<p> <h2> Place an order </h2> </p>
<form method="get" name="frmOder">
<select name="slctOrder" onChange="showDetails();">
<!-- I'm trying to call the function showDetails()
but neither onChange here nor onClick in the option tag seem to accomplish that -->
<option hidden selected="selected" value="0"> please select one of today's specials </option>
<option value="1" onClick="showDetails();"> Last of the Mo-jicama </option>
<option value="2" onClick="showDetails();"> Cheesus Is Born Burger </option>
<option value="3" onClick="showDetails();"> Beets of Burden Burger </option>
<option value="4" onClick="showDetails();"> Paranormal Pepper Jack-tivity Burger </option>
</select>
<output name="Details"/>
</form>
</body>
</html>
Couple of minor changes, but here's the working example:
update: outputting selected value into an html element vs alert.
update 2: i've changed the code to match exactly what you have but fixed some of errors to get it to work.
1) You have a typo of the form name "frmOder" but in your code, you used "frmOrder".
document.forms["frmOder"]["Details"].value = val;
2) You are trying to select the element by id but the id attribute doesn't exist:
document.getElementById("slctOrder");
Had to change:
<select name="slctOrder" onChange="showDetails();">
to:
<select id="slctOrder" onChange="showDetails();">
3) There's no need for the onclick events in the option tags.
The reason i switched out the 'output' element in my original answer is because it is not a supported tag in IE.
http://www.w3schools.com/tags/tag_output.asp
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Hot Buns </title>
</head>
<script type="text/javascript">
function showDetails()
{
var x= document.getElementById("slctOrder");
var val= x.options[x.selectedIndex].text;
document.forms["frmOder"]["Details"].value = val;
}
</script>
<body>
<p> <h2> Welcome to Hot Buns </h2> <br> <h3> Ham can we bee'f service? </h3></p>
<p> <h2> Place an order </h2> </p>
<form method="get" name="frmOder">
<select id="slctOrder" onChange="showDetails();">
<!-- I'm trying to call the function showDetails()
but neither onChange here nor onClick in the option tag seem to accomplish that -->
<option hidden selected="selected" value="0"> please select one of today's specials </option>
<option value="1"> Last of the Mo-jicama </option>
<option value="2"> Cheesus Is Born Burger </option>
<option value="3"> Beets of Burden Burger </option>
<option value="4"> Paranormal Pepper Jack-tivity Burger </option>
</select>
<output name="Details"/>
</form>
</body>
</html>
You can simplify the markup (changed portion here) and the code, adding an event listener.
Markup(revised)
<form method="get" id="frmOder">
<select id="slctOrder">
<option hidden selected="selected" value="0"> please select one of today's specials </option>
<option value="1"> Last of the Mo-jicama </option>
<option value="2"> Cheesus Is Born Burger </option>
<option value="3"> Beets of Burden Burger </option>
<option value="4"> Paranormal Pepper Jack-tivity Burger </option>
</select>
<output id="Details" />
</form>
Code
function showDetails(event) {
console.log(event);
// var x = document.getElementById("slctOrder");
var x = event.srcElement;// same as above but use the event
var val = x.options[x.selectedIndex].text;
// no need for above, just get the text value (assumes single select)
var t = event.srcElement.selectedOptions[0].text;
document.getElementById("Details").value = t;
}
// add event listener to select
var el = document.getElementById("slctOrder");
el.addEventListener("change", showDetails, false);
Note you COULD still use the name to select: (but it returns a collection so [0] needed for first one)
document.getElementsByName("slctOrder")[0];
Sample fiddle to play with:https://jsfiddle.net/MarkSchultheiss/j28cpsg9/

Keep default value and pass it on

I have the following piece of code to grab the value of a drop down list. The problem I have is that due to the onchange event attribute the first value is not passed if a user does not select an option. Is there a way I can define when there is no change the first value is passed on?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo GetSelectOptionData</title>
<select name="mySelect" id="mySelect" onchange="getSelectedValue();">
<option value="aaaaaaaaa.xml">Text 1</option>
<option value="bbbbbbbbb.xml">Text 2</option>
</select>
<form action="test">
Value1: <input id="myField" type="text" value=""><br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function getSelectedValue() {
var value = document.getElementById('mySelect').value.split('.');
document.getElementById('myField').value = value[0];
}
</script>
</body>
</html>
Many thanks!
set the first option as selected default
<option selected="selected" ...
and call getSelectedValue() after everything is defined
<script type="text/javascript">
function getSelectedValue() {
var value = document.getElementById('mySelect').value.split('.');
document.getElementById('myField').value = value[0];
}
getSelectedValue()
</script>

Javascript: how to get selected option value that is in the datalist with inside select

On this below code, Am trying to get the value of selected 'option' from 'select' element that is in the 'datalist' element. Have tried something, but, i couldn't. Am expecting solution only in javascript. As of now, it always alerts the first option value however we change the option value. It should alert actual option value when i change the option value on the input box. For example if i select 'Blueberry' then it should omit 'Bluberry'.
<html>
<head>
<title>HTML 5 test Elements</title>
</head>
<body>
<div>
<label>Your favorite fruit:
<datalist id="fruit">
<select name="fruits">
<option value="Blackberry">Blacskberry</option>
<option value="Blackcurrant">Blackcurrant</option>
<option value="Blueberry">Blueberry</option>
</select>
If other, please specify:
</datalist>
<input type="text" name="fruit" list="fruit"/>
</label>
<script type="text/javascript">
document.getElementsByName("fruit")[0].onchange = function (event) {
var evt = event || window.event;
var parElem = evt.srcElement || evt.target;
alert(document.getElementsByName("fruits")[0].options[document.getElementsByName("fruits")[0].selectedIndex].value);
}
</script>
</div>
</body>
</html>
Any idea? please.
First of all, you can remove <select> element and just keep the <datalist> and its nested <options>. Just use the datalist. Then you can use the input event to check for a change on the <input> which is connected to the datalist
Here is a working fiddle: http://jsfiddle.net/bkab62rq/
If you would like to get the alert only if the one of the preset values is used try following:
<html>
<head>
<title>HTML 5 test Elements</title>
</head>
<body>
<div>
<label>Your favorite fruit:
<datalist id="fruit">
<select id="fruits">
<option value="Blackberry">Blacskberry</option>
<option value="Blackcurrant">Blackcurrant</option>
<option value="Blueberry">Blueberry</option>
</select>
If other, please specify:
</datalist>
<input type="text" name="fruit" list="fruit"/>
</label>
<script type="text/javascript">
document.getElementsByName("fruit")[0].onchange = function (event) {
var evt = event || window.event;
var parElem = evt.srcElement || evt.target;
for (var i=0; i<document.getElementById('fruits').options.length; i++)
{
if (document.getElementById('fruits').options[i].value == document.getElementsByName("fruit")[0].value)
{
alert(document.getElementById('fruits').options[i].value);
break;
}
}
}
</script></div></body></html>
This should do the Magic ;)
Here you got an Fiddle:
http://jsfiddle.net/16e8qanz/19/
This should work
Greetz Anders

Update Textbox with Combobox value on ValueChange event

My ultimate goal with this is to make a dropdown that allows user input also. The best I can seem to do is an textbox next a dropdown that makes it look like they are similar, the issue I am running into is that I need the textbox to update whenever my dropdown value is changed. I have some code I've been playing with (below), but it doesn't seem to be getting me anywhere! Any pointers on how I can get this to work, or am I messing up the syntax? (fairly new to both jscript and html)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<style type="text/css">
select
{
width:200px;
}
</style>
<head>
<title>Test</title>
<script type="text/JavaScript">
var select = document.getElementById('theItems');
var input = document.getElementById('stroke');
function otherSelect()
{
input.value = select.value;
}
</script>
</head>
<body>
<form action="" method="">
<input name="stroke"/>
<select name="theItems" onchange="otherSelect()">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<div id="otherBox" style="visibility: hidden;">
If other: <input name="otherField" type="text" />
</div>
</form>
</body>
You should execute your script in the window.onload event. The elements are not available to your script when it is being executed. Change your script to this
<script type="text/JavaScript">
window.onload = function(){
var select = document.getElementById('theItems');
var input = document.getElementById('stroke');
function otherSelect()
{
input.value = select.value;
}
}
</script>
This way the script will be executed after the HTML elements have been rendered by the browser.
Here's a simple pure JavaScript implementation of what you want. http://jsfiddle.net/24Xhn/
We're going to setup the markup so the select box and the other input box have similar name and id attributes. We'll use classes to setup/initialize the onchange events and make sure the inputs start off hidden and disabled. By toggling the "disabled" attribute, true or false we are making it so the input or select don't show up when the form is submitted, submit the form in the JSFiddle with different combinations and you'll see the output in the query string of the URL.
HTML
<select id="items1" name="items1" class="select-other">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<input id="items1-other" name="items1-other" class="input-other" />
JS
// setup
var inps = document.getElementsByClassName("input-other");
for(var i=0; i<inps.length; i++) {
var inp = inps[i];
// hide & disable the "other" input
inp.style.display = "none";
inp.disabled = true;
// set onchange, if input is empty go back to select
inp.onchange = function() {
var val = this.value;
if(val == "") {
this.style.display = "none";
this.disabled = true;
// get its associated select box
var sel = document.getElementById(this.id.replace(/-other$/i, ""));
sel.style.display = "";
sel.disabled = false;
}
};
}
var sels = document.getElementsByClassName("select-other");
for(var i=0; i<sels.length; i++) {
var sel = sels[i];
// set onchange if value is other switch to input
sel.onchange = function() {
var val = this.value;
if(val == "other") {
this.style.display = "none";
this.disabled = true;
// get associated input box
var inp = document.getElementById(this.id + "-other");
inp.style.display = "";
inp.disabled = false;
}
};
}
I just realized what was wrong. I didn't truly look at the html until I copied and pasted it into a test application and I figured out the issue.
You need to set the id tag to the stroke and theItems not the name tag. That's why it's not doing anything. There was, I'm guessing, a copy/paste issue as well because you didn't have a closing html tag, but I assumed you just missed copying that. Also, you don't really need global variables in order to retrieve the input and select you just need them inside the actual function, and you can actually pass the select into the function like so.
Your code corrected:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</title>
<style type="text/css">
select
{
width:200px;
}
</style>
<script type="text/javascript">
function otherSelect(obj)
{
var input = document.getElementById('stroke');
input.value = obj.value;
}
</script>
</head>
<body>
<form action="" method="">
<input id="stroke" name="stroke"/>
<select id="theItems" name="theItems" onchange="otherSelect(this)">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<div id="otherBox" style="visibility: hidden;">
If other: <input name="otherField" type="text" />
</div>
</form>
</body>
</html>
I also wanted to create a combobox with an auto-updating text field next to it for new entries, and came up with this in less than an hour, based on simple html and javascript examples from w3schools.com. It works perfectly on my IE browser.
<!DOCTYPE html>
<html>
<head>
<script>
function updateField(name, value)
{
document.getElementById(name).value = value;
}
</script>
</head>
<body>
<select name='10' onchange='updateField(this.name, this.value)'>
<option value='volvo'>Volvo</option>
<option value='saab'>Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="text" id="10" value="volvo">
</body>
</html>

How do I add JavaScript code on a webpage?

Could someone please tell me how to get this code working on a webpage? Particularly what should go in the header?
http://jsfiddle.net/mekwall/TJcP4/1/
Sorry if this is a basic question...steep learning curve!
Thanks
Your code is using the jQuery JavaScript library ... so your head will need to contain :
<script type="text/javascript" src="<jquery url>"></script>
Replace the <jquery url> with a valid url to the jQuery library. I suggest you use the Google CDN for the url or alternatively download a copy and store it on your server -> http://docs.jquery.com/Downloading_jQuery#Download_jQuery
Then to ensure your code runs once the DOM is ready wrap all of your JavaScript within the following :
$(document).ready(function() {
// your code here
});
Docs for ready() here
If your going to be using jQuery more I suggest you start reading here http://docs.jquery.com/How_jQuery_Works and if you going to learn JavaScript, you can't go wrong with reading this too -> https://developer.mozilla.org/en/JavaScript/Guide
Copy the code below, save it with a .html extension (e.g. test.html) and then double click to open.
<html>
<head>
<title>Page Title here</title>
</head>
<body>
<select id="t_dermal_name">
<option value="t_default_dermal">-- Choose --</option>
<option value="1" rel="30">Between Eyebrows</option>
<option value="7" rel="30">Individual Line Softening</option>
<option value="2" rel="30">Lip Contouring</option>
</select>
<select id="t_wrinkle_name">
<option value="t_default_wrinkle">-- Choose --</option>
<option value="1" rel="30">Between Eyebrows</option>
<option value="7" rel="30">Individual Line Softening</option>
<option value="2" rel="30">Lip Contouring</option>
</select>
<span id="output"></span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script><!--You can use a local version of jquery-->
<script type="text/javascript">
$(document).ready(function(){
function onSelectChange(){
var total = 0,
dermal = $("#t_dermal_name").find('option:selected'),
wrinkle = $("#t_wrinkle_name").find('option:selected');
if(value = dermal.attr('rel')){
total += parseInt(value);
}
if(value = wrinkle.attr('rel')){
total += parseInt(value);
}
$("#output").html(total);
}
$("#t_dermal_name").change(onSelectChange);
$("#t_wrinkle_name").change(onSelectChange);
});
</script>
</body>

Categories