Javascript Guide

Form Manipulation

April 2, 2010

Text Fields - How to Get Default Value

On the previous page, I had a default value for the name field "enter your name." Sometimes, you want a default value that is valid and you need to assign that value to a variable for Javascript. In order to do that, you need to get this value first. Here is an example that has a default value and how to get this value with a Javascript function.

HTML Dose: <input type="text" size="4" value="1000" /> mg <br /> Interval: <input type="text" size="4" value="12" /> hr <br/>
Dose: mg
Interval: hr

I have written a function called getObj that returns the object we seek. Then we can determine the value of that object.

Javascript - examples.js function getObj(node) {return document.getElementById(node); } HTML <p>Write dose here: <span id="dose_val"> ?? </span> mg every <span id="int_val"> ?? </span> hours </p> <input type="button" value="Get Dose" onclick="var mydose = getObj('dose').value;changeValue('dose_val',mydose); var myint = getObj('int').value;changeValue('int_val',myint);" />

Write dose here: ?? mg every ?? hours

Notes on the above example:

  • I created span elements with id's where the dose and interval will go.
  • The function getObj is a simple function that simply returns the object name. We use the object name to assign the object's value to a variable in the HTML onclick event.
  • I have used the changeValue function that we learned about earlier to change the value in the span elements we created.

How to Write Values to Fields

We have learned how to write values to non-field elements such as a paragraph or span element. However, we can also write values to form fields as well. The same function that we use to get the value can be used to write the value to a form field. Unlike using .firstChild and .nodeValue properties, we simply use the .value property. Here is an example on how to write to a form field.

HTML <label>First name: </label> <input id="fname" type="text" size="10" /> <br/> <label>Last name: </label> <input id="lname" type="text" size="10" /> <br/> <label> Full name: </label> <input id="fullname" type="text" size="15"> <br/> <input type="button" value="Write Name" onclick="getObj('fullname').value = getObj('fname').value + ' ' + getObj('lname').value" />

Notes on examples above:

  • Using getObj('object').value on left side of equal will make the value of that object equal to what is on the right side of equal.
  • I didn't assign any variables on right side of equal since I don't need to pass any values to another function.