?
Solved

Javascript - Convert between Liters and Gallons

Posted on 2014-04-04
12
Medium Priority
?
755 Views
Last Modified: 2014-06-01
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
Comment
Question by:FrostyGirl
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
12 Comments
 
LVL 53

Accepted Solution

by:
Scott Fell,  EE MVE earned 2000 total points
ID: 39978522
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>
<head>
<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>
</head>
<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>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 39978579
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>
</head>
<body>
<input type="text" id="input_ID" />
<br />
<input type="radio" id="radio1_ID" name="radio" />
<br />
<input type="radio" id="radio2_ID" name="radio" />
<br />
<input type="text" id="result_ID" />

Open in new window

0
 

Author Comment

by:FrostyGirl
ID: 39978594
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:FrostyGirl
ID: 39978600
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 53

Expert Comment

by:Scott Fell, EE MVE
ID: 39978639
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

by:FrostyGirl
ID: 39978652
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

by:FrostyGirl
ID: 39978658
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

by:Peter_Toretto
ID: 39979699
Hi,

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

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            
       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 53

Expert Comment

by:Scott Fell, EE MVE
ID: 39979751
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

by:Sar1973
ID: 39982408
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;
}
}

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
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…
Suggested Courses

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

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

Join & Ask a Question