Solved

# Javascript - Convert between Liters and Gallons

Posted on 2014-04-04
554 Views
Hello,

I need a javascript function that will convert values from liters to gallons, and vice versa, when a user selects 1 of 2 radio button choices:  Imperical / Metric.  Whichever values I have tagged with a CSS value unitConvert should switch.  So if the metric value is 8, then it would be converted 8 * 0.26417 = 2.11 gallons.  If it were 4 gallons it would be converted:  4 * 3.7854 = 15.14 gallons.

Are there any examples / scripts that exist?

Also, I'm a rank amateur when it comes to .js.

Thanks,
Anja
0
Question by:FrostyGirl

LVL 52

Accepted Solution

Scott Fell,  EE MVE earned 500 total points
Let me know if you need help following this.  I used jquery so you will need to add jquery to your server or use it from the CDN as I have done here.

This is a working sample http://jsbin.com/zufodego/1/edit?html,output
``````<!DOCTYPE html>
<html>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
\$(function () {
// set values
var toGallons = 0.26417;
var toMetric = 3.7854;
var converted = 0;
\$('input[name="data"]').change(function () {
// if enter a new value, convert
convert();
});
\$('input[name="convert"]').change(function () {
// if change radio, convert
convert();
});

function convert() {
var theValue = \$('input[name="data"]').val();  //value of original
var selected = \$("input[type='radio'][name='convert']:checked").val();  //determine if Metric or Imperial

if (selected === 'i') { //If imperial
converted = "The Imperial Value of  " + theValue + " = the metric value of " + theValue * toMetric;
} else {//If metric
converted = "The Metric Value of  " + theValue + " = the Imperial value of " + theValue * toGallons;
}
\$('#newData').html(converted);  //Place new data in div id newData

}
});
</script>
<meta charset="utf-8">
<title>JS Bin</title>
<body>
<input type="radio" name="convert" value="m">Metric
<input type="radio" name="convert" value="i" checked>Imperial
<div>Data<br><input name="data" value="0"> </div>

<div>Converted</div><div id="newData"></div>

</body>
</html>
``````
0

LVL 82

Expert Comment

Test page : http://jsfiddle.net/2hsND/

``````<script>
window.onload = function() {

document.getElementById("radio1_ID").onchange = function() {
document.getElementById("result_ID").value = document.getElementById("input_ID").value * 0.26417;
}
document.getElementById("radio2_ID").onchange = function() {
document.getElementById("result_ID").value = document.getElementById("input_ID").value * 3.7854;
}

}
</script>
<body>
<input type="text" id="input_ID" />
<br />
<br />
<br />
<input type="text" id="result_ID" />
``````
0

Author Comment

Hi,

It's very close, thank you!  It needs to work like this:
http://jsfiddle.net/#&togetherjs=wcHkUpizUs

Which it currently doesn't, of course (b/c I modified your code and broke it).
0

Author Comment

Here's the code in case the fiddle didn't work:

<script>
\$(function() {
// set values
var toGallons = 0.26417;
var toMetric = 3.7854;
var converted = 0;
\$('input[name="data"]').change(function() {
// if enter a new value, convert
convert();
});
\$('input[name="convert"]').change(function() {
// if change radio, convert
convert();
});

function convert() {
var theValue = \$('input[name="data"]').val(); //value of original
var selected = \$("input[type='radio'][name='convert']:checked").val(); //determine if Metric or Imperial

if (selected === 'i') { //If imperial
converted = theValue * toMetric;
} else { //If metric
converted = theValue * toGallons;
}
\$('#newData').html(converted); //Place new data in div id newData

}
});
</script>
<title>JS Bin</title>
<body>
<input type="radio" name="convert" value="m">Metric
<input type="radio" name="convert" value="i" checked>Imperial
<div>
<br><span name="data" value="8">8</span>//This needs to flip back and forth from imperial to metric depending on the radio selection
<span id="newData"></span>

</body>
0

LVL 52

Expert Comment

I placed it in jsfiddle for you http://jsfiddle.net/hLCd8/2/

You have to add jquery on the left, just the html inside the body on top and no need for a <script> tag on the bottom.

Each time you modify, click the update at the top. That way if you break it you can go back and start over, click update again and you are starting fresh.

Good luck!
0

Author Comment

Hi,

This would work, http://jsfiddle.net/2hsND/, but input_ID and result_ID should be only 1 field.  I pre-populate the field based on whatever product a user selected.  It would look like this

Left Column:  Metric | Imperial ?

Center Column:  Step Response:  8 liters  (or Step Response: 30.28 gallons... depending on metric or imperial selection.  metric is default choice)
0

Author Comment

To clarify, 8 would be the start value, and the start measurement is liters (metric).  The value is pre-populated so the converter changes the value to whatever the other choice is.  So if I select gallons (imperial) the value would update to 30.28, and if I hit liters (metric), the value would return to 8.
0

Expert Comment

Hi,

Though I am a learner in this field, I guess the following code can be helpful for you: -

System.out.println();
System.out.print("\t====================================\n");
System.out.print("\t====== Liters To Gallons ==========\n");
System.out.print("\t====== Converter Version 1.0========\n");
System.out.print("\t====================================\n");
System.out.println();
System.out.print("Enter the Liters :=>");
int liter = Integer.parseInt(bf.readLine());
double gallon = liter * 0.264172052358148;
System.out.println();
System.out.println("In Gallons :=> " + gallon);
System.out.println();

Regards..
0

LVL 52

Expert Comment

You can pre populate the data by directly inserting a value to the form field.

To start with a value of 8,
<input type="text" id="input_ID" value="8" />

To pre populate the radio button, added the word, checked like this,
<input type="radio" name="convert" value="i" checked>

You have some good options, now you just need to make your front end.
0

LVL 9

Expert Comment

With JS (assuming your HTML has a checkbox named "mySystem" with the 2 options metric/imperial and a input textbox with ID "myValue" where the value is typed), assign an onchange event to the checkbox that performs/calls this function:
``````function myConversion() {
var myCKB = document.getElementsByName("mySystem")[0];
var myNVL=document.getElementById("myValue");
if (myCKB.checked) {
document.getElementById("myValue")=myNVL.value*0.26417;
} else {
document.getElementById("myValue")=myNVL.value* 3.7854;
}
}
``````
0

## Join & Write a Comment Already a member? Login.

### Suggested Solutions

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

#### 772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

#### Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!