Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing HTML Form Data to Javascript Function

I've created a form with one drop down menu to choose from as well as three other text fields for users to input data.

I need to perform calculations on the data the user inputs and then display the results.

For now, I just want to be able to pass the results into the function and print the results. From there I'll figure out how to display those outputs into a table.

Right now, I'm having trouble identifying the specific element's value. With the drop down menu I'm able to identify the chosen value by writing document.getElementById("activity_level").value. The rest of the values won't appear when I run the function. I'm assuming that I'm not identifying the value type so the browser knows what the display is.

Here is my HTML:

<form>
        Activity Level: <select id="activity_level">
                        <option value="null">Please Choose One...</option>
                        <option value="1.25">Practically a Vegetable</option>
                        <option value="1.35">Mostly Desk Work and Light Walking</option>
                        <option value="1.55">Moderate Exercise 2-3 Times Per Week</option>
                        <option value="1.75">Heavy Exercise 3-4 Times Per Week</option>
                        <option value="1.95">Committed Hardcore Athlete</option>
                        </select></br>
        BodyFat Percentage <input type="text" id="bfp" /> </br>
        Total Weight <input type="text" id="tw" /></br>
        Target Bodyfat Percentage <input type="text" id="target_bodyfat_pct" /></br>
        <input type="button" value="Calculate" onclick="Calculate()" />
    </form>

Here is my javascript:

 <script type="text/javascript">

    function Calculate(){
        //document.write(bfp + "</br>");
        document.write(document.getElementById("activity_level").value + "</br>");
        //document.write(document.getElementById("tw") + "</br>");
        //document.write(document.getElementById("target_bodyfat_pct"));
    }

    </script>
like image 511
Nick Res Avatar asked Dec 17 '11 19:12

Nick Res


1 Answers

You need to reference the value property on your inputs, just like you did with your select

document.write(document.getElementById("target_bodyfat_pct"));
document.write(document.getElementById("tw") + "</br>");

should be

document.write(document.getElementById("target_bodyfat_pct").value);
document.write(document.getElementById("tw").value + "</br>");

Also, consider creating a div for all the output, and writing it there.

<div id="yourOutputDiv"></div>

var results = document.getElementById("activity_level").value + "</br>" +
              document.getElementById("target_bodyfat_pct").value + 
              document.getElementById("tw").value + "</br>";

document.getElementById("yourOutputDiv").innerHTML = results;
like image 151
Adam Rackis Avatar answered Oct 19 '22 14:10

Adam Rackis