JavaScript:Forms

From virtualMV2015wiki
Jump to: navigation, search
 Home  JavaScript <

Overview

To invoke JavaScript activity from a form we usually use a button to call a function

<input type = 'button' value = 'Press Me' onClick = 'fnFunction()'/>

We can add JavaScript interaction to any form element using one of the following:

onfocus=Script (element received focus)
onblur=Script (element lost focus)
onselect=Script (element text selected)
onchange=Script (element value changed)

Within JavaScript we can refer to any form element and assign the value of them to variables which we can use within our code

Input box

Example (js2_01)

<html>
<head>
  <style type="text/css">.lbl { width: 200px; float:left;}</style>
</head>
<body>
<script type="text/javascript">
<!--
function fnDisplayName() {
    strMessage=document.myForm.txtFname.value;
    strMessage=strMessage +" " +document.myForm.txtLname.value;
    alert("Hello " + strMessage);
}
//-->
</script>
<form name="myForm">
<p><span class="lbl">Enter Your First Name:</span>
  <input type="text" name="txtFname" value="" /></p>
<p><span class="lbl">Enter Your Last Name:</span>
  <input type="text" name="txtLname" value="" /></p>
<p><span class="lbl">&nbsp;</span>
<input type="button" value="Press Me" onClick="fnDisplayName()" /></p>
</form></body>
</html>
  • Note: The css .lbl is used to space out the labels.
  • Warning** IE has another (feature) - you need to leave a space between the onClick string and "/>"

Example js2_01

Example (js2_02)

<html><body>
<script type="text/javascript">
<!--
function fnDisplaySum() {
    vntNum1=eval(document.myForm.txtVal1.value);
    vntNum2=eval(document.myForm.txtVal2.value);
    vntSum=vntNum1+vntNum2;
    document.myForm.txtResult.value=vntSum;
}
//-->
</script>
<form name="myForm">
  Enter Your first number:&nbsp;
    <input type="number" name="txtVal1" value="0" /><br />
  Enter Your second number:&nbsp;
    <input type="number" name="txtVal2" value="0" /><br />
  <input type="button" value="Calculate Sum" onClick= "fnDisplaySum()" /><br />
  The result is:&nbsp;<input type="number" name="txtResult" /><br />
</form>
</body></html>

Example js2_02

select (js2_03)

<html></body>
<script type="text/javascript">
<!--
function fnDisplaySelect() {
  frmRef=document.frmChoose.cboNumber; //this means we don't need to key as much on the next line
  intSelectvalue=frmRef.options[frmRef.selectedIndex].value;
  alert("You chose the number " + intSelectvalue);
}
//-->
</script>
<form name="frmChoose">
  <select name="cboNumber">
    <option value="10">Ten</option>
    <option value="20">Twenty</option>
    <option value="30">Thirty</option>
  </select>
  <input type="button" value="Display Selection" 
         onClick="fnDisplaySelect()" />
</form>
</body></html>

Example js2_03

Radio button (js2_04)

<html><body>
<script type="text/javascript">
<!--
function fnCheck() {
if (document.frmChoose.radVal[0].checked) {
  alert("You chose the Add operation");}
if (document.myForm.radVal[1].checked) {
  alert("You chose the Subtract operation");}
}
//-->
</script>
<form name="frmChoose">
  <p>Select an operation:</p>
  <p><input type="radio" name="radVal" value="Add" />Add</p>
  <p><input type="radio" name="radVal" value="Subtract" />Subtract</p>
  <input type="button" value="Press Me" onClick="fnCheck()" />
</form>
</body></html>

Example js2_04

Check box (js2_05)

<html><body>
<script type="text/javascript">
<!--
function fnCheck() {
  var strX = "";
  chkDrink=document.frmChoose.chkDrinks;
  if (chkDrink[0].checked) {strX = strX + chkDrink[0].value +" ";};
  if (chkDrink[1].checked) {strX = strX + chkDrink[1].value +" ";};
  if (chkDrink[2].checked) {strX = strX + chkDrink[2].value + " ";};
  alert("You have selected: " +strX);
}
//-->
</script>
<form name="frmChoose">
<input type="checkbox" name="chkDrinks" value="milk" />Milk<br />
<input type="checkbox" name="chkDrinks" value="cream" />Cream<br />
<input type="checkbox" name="chkDrinks" value="sugar" />Sugar<br />
<input type="button" value="Order" onClick="fnCheck()" />
</form>
</body></html>

Example :Click here to run js2_05.htm.

Summary (js2_06)

<!doctype html public "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>JavaScript forms - summary</title>
<script type="text/javascript">
<!--
function fnCalcVal() {
   vntNumber = eval(document.frmCalc.txtNumber.value);
   vntFormVal = document.frmCalc.cboVal;
   vntSelectvalue = vntFormVal.options[vntFormVal.selectedIndex].value;
   document.frmCalc.txtValue.value = vntSelectvalue;
   vntResult = vntNumber*vntSelectvalue;
   document.frmCalc.txtResult.value=vntResult;
}
//-->
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<form name="frmCalc">
  Enter a number:<input type="text" value="0" name="txtNumber" /><br />
  Select a value:
  <select name="cboVal" onChange="fnCalcVal()">
    <option value=10>Ten</option>
    <option value=20>Twenty</option>
    <option value=30>Thirty</option>
  </select><br />
  Value: <input type="text" value="0" name="txtValue"  disabled="disabled" />
        Result: <input type="text" value="0" name="txtResult" disabled="disabled" /><br />
</form>
</body>
</html>

Note: Use of disabled means the text boxes cannot be changed by a user

Example js2_06

Validating and displaying a different background if an error

Note: this has been added by a user and needs a little tidying up :)

In an html document, create a form ( call 'Form1' )

The forms action is to post the information entered in the form to 'someone@somewhere.co.nz' and create a message to let the user know this action is happening

<form id="Form1" name="Form1" action="mailto:someone@somewhere.co.nz?subject=Booking" method="post" 
enctype="text/plain" onSubmit="alert('Booking sent to \n \'someone@somewhere.co.nz\'');"></form>

Within the form;

Create a text box (called 'Name1') to be filled in (Lists are used to create this form but other methods can be used).

Include a trigger to call the JavaScript (onblur="fnNameOK()) within the html code.

Create a location (called 'ErrorName') for the error message to appear.

<li class="list1"><label for "Name1"><span class="red">* </span>Your Name</label><input type="text" 
id="Name1" name="Name1" style="width: 11em" tabindex="1" onblur="fnNameOK()"/> <span class="grey">
First and Last Name</span></li> 
<p id = "ErrorName"></p>

The CSS looks like this

.list1          {padding: .1em; list-style-type:none; } /*Sets property for lists */
.list1 label    {float: left; width: 7em;/*length assigned to words*/ margin-right: .6em;/*length 
between word area and textbox*/}
#errorName	{font-size: 85%; color: #b57600; margin-left:12em}
.red		{color:#ff0000;}
.Error		{font-size: 70%;}

The form should look something like this

Sample of JavaScript with mandatory fields indicated

Create a JavaScript form

Set up a variable called 'errorOne' that contains the text you want to display

var errorOne = document.createTextNode("Please enter your First Name, a gap then your Last Name");

Set up a variable to check for letters only (or change the * to a + to check for letters and gaps if desired (Both are shown))

var varLettersExpression = /^[a-zA-Z\s]*$/; /* Expression to check for letters and gaps*/
var varLettersExpression = /^[a-zA-Z\s]+$/; /* Expression to check for letters no gaps*/

Next set up the 'fnNameOK()'

function fnNameOK()// function to call check the user name
 {
var varName = document.Form1.Name1.value;//obtain value
if (!varName.match(varLettersExpression) || varName=="") //If no letters or invalid entry
 {
document.Form1.Name1.style.background ="#f1a629";//change background color
document.Form1.Name1.value="";//set value to null
document.getElementById("ErrorName").appendChild(errorOne); //Insert error message
return false// stop here
 }
 else {// if all ok
document.Form1.Name1.style.background ='#ffffff';//change background color
document.getElementById("errorName").removeChild(errorOne); //Remove error message
 return true}
 }

The form should look something like this when no data or incorrect data has been entered and the cursor changes focus away from the text box

Sample of JavaScript with errors in fields indicated

Note: The lines of code 'document.Form1.Name1' and 'document.getElementById("Name1")' often acheive similar results.

Icon References.png References


JavaScript:Forms. (2017). In virtualMV's ( Michael Verhaart ) wiki. Retrieved December 17, 2017, from http://www.virtualmv.com/wiki/index.php?title=JavaScript%3AForms    (zotero)