CH 3 - Lecture Notes
CH 3 - Lecture Notes
https://learn-the-web.algonquindesign.ca/topics/forms-cheat-sheet/#input-types
required
o Define the input as being compulsory.
o <input id="dino" required>
checked
o Whether the radio or checkbox are selected.
o <input type="checkbox" id="dino" checked>
value="…"
o Puts a default value into the field.
o <input type="range" value="4" id="dino">
placeholder="…"
FOR JavaScript
https://htmlcheatsheet.com/js/
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
Output
onsubmit Event Type
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form
will be submitted, otherwise it will not submit the data.
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
Output
HTML 5 Standard Events
The standard HTML 5 events are listed here for your reference. Here script indicates a
Javascript function to be executed against that event.
https://www.infoworld.com/article/2077176/using-javascript-and-forms.html
Nothing strikes more fear in the heart of a Web publisher than these three letters: C-G-I. CGI
(which stands for common gateway interface), is a mechanism for safely transporting data
from a client (a browser) to a server. It is typically used to transfer data from an HTML form
to the server.
With JavaScript at your side, you can process simple forms without invoking the server. And
when submitting the form to a CGI program is necessary, you can have JavaScript take care
of all the preliminary requirements, such as validating input to ensure that the user has dotted
every i. In this column we'll look closely at the JavaScript-form connection, including how to
use JavaScript's form object, how to read and set form content, and how to trigger JavaScript
events by manipulating form controls. We'll also cover how to use JavaScript to verify form
input and sumbit the form to a CGI program.
Typical form control objects -- also called "widgets" -- include the following:
I won't bother enumerating all the attributes of these controls (widgets), and how to use them
in HTML. Most any reference on HTML will provide you with the details. For use with
JavaScript, you should always remember to provide a name for the form itself, and each
control you use. The names allow you to reference the object in your JavaScript-enhanced
page.
The typical form looks like this. Notice I've provided NAME= attributes for all form controls,
including the form itself:
FORM NAME="myform" defines and names the form. Elsewhere in the JavaScript you can
reference this form by the name myform. The name you give your form is up to you, but it
should comply with JavaScript's standard variable/function naming rules (no spaces, no weird
characters except the underscore, etc.).
ACTION="" defines how you want the browser to handle the form when it is submitted to a
CGI program running on the server. As this example is not designed to submit anything, the
URL for the CGI program is omitted.
METHOD="GET" defines the method data is passed to the server when the form is
submitted. In this case the atttibute is puffer as the example form does not submit anything.
INPUT TYPE="text" defines the text box object. This is standard HTML markup.
INPUT TYPE="button" defines the button object. This is standard HTML markup except for
the onClick handler.
onClick="testResults(this.form)" is an event handler -- it handles an event, in this case
clicking the button. When the button is clicked, JavaScript executes the expression within the
quotes. The expression says to call the testResults function elsewhere on the page, and pass to
it the current form object.
Listing 1. testform.html
<HTML>
The testResults function is simple -- it merely copies the contents of the text box to a variable
named TestVar. Notice how the text box contents was referenced. I defined the form object I
wanted to use (called form), the object within the form that I wanted (called inputbox), and
the property of that object I wanted (the value property).
Listing 2. set_formval.html
<HTML>
<HEAD>
<TITLE>Test Input </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function readText (form) {
TestVar =form.inputbox.value;
When you click the "Read" button, JavaScript calls the readText function, which reads and
displays the value you entered into the text box.
When you click the "Write" button, JavaScript calls the writeText function, which writes
"Have a nice day!" in the text box.
Following is an example of testing which button is selected. The for loop in the testButton
function cycles through all of the buttons in the "rad" group. When it finds the button that's
selected, it breaks out of the loop and displays the button number (remember: starting from
0).
LIsting 3. form_radio.html
<HTML>
<HEAD>
<TITLE>Radio Button Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testButton (form){
for (Count = 0; Count < 3; Count++) {
if (form.rad[Count].checked)
break;
}
alert ("Button " + Count + " is selected");
}
</SCRIPT>
</BODY>
<FORM NAME="testform">
<INPUT TYPE="button" NAME="button" Value="Click"
onClick="testButton(this.form)"> <BR>
<INPUT TYPE="radio" NAME="rad" Value="rad_button1" onClick=0><BR>
<INPUT TYPE="radio" NAME="rad" Value="rad_button2" onClick=0><BR>
<INPUT TYPE="radio" NAME="rad" Value="rad_button3" onClick=0><BR>
</FORM>
</HTML>
Setting a radio button selection with HTML market is simple. If you want the form to initially
appear with a given radio button selected, add the CHECKED attribute to the HTML markup
for that button:
You can also set the button selection programmatically with JavaScript, using the checked
property. Specify the index of the radio button array you want to checked.
Listing 4. form_check.html
<HEAD>
<TITLE>Checkbox Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testButton(form) {
alert(form.check1.checked);
}
</SCRIPT>
<BODY>
<FORM NAME="testform">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testButton(this.form)"><BR>
<INPUT TYPE="checkbox" NAME="check1" Value="Check1">Checkbox 1<BR>
<INPUT TYPE="checkbox" NAME="check2" Value="Check2">Checkbox 2<BR>
<INPUT TYPE="checkbox" NAME="check3" Value="Check3">Checkbox 3<BR>
</FORM>
</BODY>
</HTML>
As with the radio button object, add a CHECKED attribute to the HTML markup for that
check box you wish to be initially check when the form is first loaded.
You can also set the button selection programmatically with JavaScript, using the checked
property. Specify the name of the checkbox you want to check, as in
form.check1.checked = true;
Text areas are used for multiple-line text entry. The default size of the text box is 1 row by 20
characters. You can change the size using the COLS and ROWS attributes. Here's a typical
example of a text area with a text box 40 characters wide by 7 rows:
Listing 5. form_textarea.html
<HTML>
<HEAD>
<TITLE>Text Area Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function seeTextArea(form) {
alert(form.myarea.value);
}
</SCRIPT>
</HEAD>
</HTML>
You can preload text into the text area in either of two ways. One method is to enclose text
between the <TEXTAREA> and </TEXTAREA> tags. This method is useful if you wish to
include hard returns, as these are retained in the text area box. Or, you can set it
programmatically with JavaScript using the following syntax:
The list can appear with many items showing at once, or it can appear in a drop-down box --
normally you see one item at a time, but click to see more. The markup for the two styles is
identical, except for the optional SIZE attribute. Leave off SIZE to make a drop-down box;
use SIZE to make a list box of the size you wish.
Use the selectedIndex property to test which option item is selected in the list, as shown in
the following example. The item is returned as an index value, with 0 being the first option, 1
being the second, and so forth (if no item is selected the value is -1).
Listing 6. form_select.html
<HTML>
<HEAD>
<TITLE>List Box Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testSelect(form) {
alert(form.list.selectedIndex);
}
</SCRIPT>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="button" NAME="button" Value="Test"
onClick="testSelect(this.form)">
<SELECT NAME="list" SIZE="3">
<OPTION>This is item 1
<OPTION>This is item 2
<OPTION>This is item 3
</SELECT>
</FORM>
</BODY>
</HTML>
If you want the text of the selected list item instead of the index, use this in the testSelect
function:
onFocus -- an event is triggered with a form object gets input focus (the insertion point is
clicked there).
onBlur -- an event is triggered with a form object loses input focus (the insertion point is
clicked out of there).
onChange -- an event is triggered when a new item is selected in a list box. This event is also
trigged with a text or text area box loses focus and the contents of the box has changed.
onSelect -- an event is triggered when text in a text or text area box is selected.
onSubmit -- an event is triggered when the form is submitted to the server (more about this
important hander later in the column).
Place the onSubmit event hander in the <FORM> tag. This tells JavaScript what it should do
when the user clicks the Submit button (this is a button defined as TYPE="submit").
Using onSubmit
Here's an example of using the onSubmit event handler to send mail. The onSubmit event
handler tells JavaScript what to do when the user clicks the Submit button: call the mailMe()
function, where additional mail fields are appended to a mailto: URL. Navigator
automatically opens a new mail window with the fields filled in. Write the body of the
message, and send the mail off to the recipient.
Listing 7. onsubmit.html
<HTML>
<HEAD>
<TITLE>onSubmit Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function mailMe(form) {
Subject = document.testform.inputbox1.value;
CC = document.testform.inputbox2.value;
BCC = document.testform.inputbox3.value;
location = "mailto:[email protected]?
subject=" + Subject + "&Bcc=" +
BCC + "&cc=" + CC;
return true;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="testform" onSubmit="return
mailMe(this.form)">Subject of message: <BR>
<INPUT TYPE="text" NAME="inputbox1" VALUE="This is
such a great form!" SIZE=50>
<P>Send cc to: <BR>
<INPUT TYPE="text" NAME="inputbox2" VALUE=""
SIZE=50>
<P>
Send blind cc to: <BR>
<INPUT TYPE="text" NAME="inputbox3" VALUE=""
SIZE=50>
<P>
<INPUT TYPE="submit"><BR>
</FORM>
</BODY>
Using submit
In the next example the submit method is used instead. The script is little changed, except
that the onSubmit handler is removed, and an onClick hander for a renamed form button is
added in its place. The submit() method replaces the return true statement in the previous
example. (Personally, I prefer the submit method because it provides a little more flexibility.
But either one will work.)
Listing 8. submit.html
<HTML>
<HEAD>
<TITLE>test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function mailMe(form) {
Subject = document.testform.inputbox1.value
CC = document.testform.inputbox2.value
BCC = document.testform.inputbox3.value
location = "/javaworld/cgi-bin/jw-mailto.cgi?
[email protected]?subject=" + Subject + "&Bcc=" +
BCC + "&cc=" + CC
document.testform.submit();
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="testform">
Subject of message: <BR>
<INPUT TYPE="text" NAME="inputbox1" VALUE="This is
such a great form!" SIZE=50>
<P>
Send cc to: <BR><INPUT TYPE="text"
NAME="inputbox2" VALUE="" SIZE=50>
<P>
Send blind cc to: <BR><INPUT TYPE="text"
NAME="inputbox3" VALUE="" SIZE=50>
<P>
<INPUT TYPE="button" VALUE="Send Mail"
onClick="mailMe()"><BR>
</FORM>
</HTML>
The typical form as used on a Web page consists of two parts: the form itself, which is
rendered in the browser, and a CGI script or program located on the server. This script
processes the user's input. While it's not exactly rocket science, a stumbling block in creating
great Web forms is writing the CGI program. In most cases these programs are written in Perl
or C, and can be a bother to implement and debug. A primary job of the CGI program is to
validate that the reader has provided correct data, and this can requires pages of code.
JavaScript changes that. With JavaScript you can check the data provided by the reader
before it's ever sent to the CGI program. In this way the CGI program can be kept to a bare
minimum. And, because the data is only sent after it has been validated, the server need not
be bothered until the form entry is known to be good. This saves valuable server resources.
Most form validation chores revolve around basic data checking: does the user remember to
fill in an box? Is it have the right length? Does it contain valid characters? With most forms
you can readily answer these questions with a small handful of validation routines.
A typical validation routine is determining if an input box contains only numeric digits,
shown below. If the entry contains non-numeric characters, you can ask the user to enter the
correct data. A ready-made routine for this is the isNumberString function, which returns the
value 1 if the string contains only numbers, and 0 if it contains any non-numeric characters.
To use it, provide the data string as the parameter. The value returned by the function tells
you if the data is valid.
Listing 9. valid_simple.html
<HTML>
<HEAD>
<TITLE>Test Input Validation</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults(form) {
TestVar = isNumberString(form.inputbox.value)
if (TestVar == 1)
alert("Congratulations! You entered only
numbers");
else
alert("Boo! You entered a string with non-
numbers characters");
}
function isNumberString(InString) {
<BODY>
<FORM NAME="myform">
Enter a string with numbers only:
<INPUT TYPE="text" NAME="inputbox" VALUE="">
<INPUT TYPE="button" NAME="button" Value="Click"
onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
Conclusion
The traditional way to use forms on a Web page is to send all the user's entries to a CGI script
or program running on the server. The bulk of most any CGI program is verifying that the
user entered valid data. Entry validation is something JavaScript can do, and do very easily.
By using JavaScript you can greatly reduce the complexity of writing and implementing CGI
programs. And, in many cases JavaScript, can completely supplant CGI programs, taking the
burden off the server by relieving it of mundane processing chores.
Here, we will learn the method to access the form, getting elements as the JavaScript
form's value, and submitting the form.
Introduction to Forms
Forms are the basics of HTML. We use HTML form element in order to create
the JavaScript form. For creating a form, we can use the following sample code:
1. <html>
2. <head>
3. <title> Login Form</title>
4. </head>
5. <body>
6. <h3> LOGIN </h3>
7. <form name="Login_form" onsubmit="submit_form()">
8. <h4> USERNAME</h4>
9. <input type="text" placeholder="Enter your email id"/>
10. <h4> PASSWORD</h4>
11. <input type="password" placeholder="Enter your password"/></br></br>
12. <input type="submit" value="Login"/>
13. <input type="button" value="SignUp" onClick="create()"/>
14. </form>
15. </html>
In the code:
o Form name tag is used to define the name of the form. The name of the form here is
"Login_form". This name will be referenced in the JavaScript form.
o The action tag defines the action, and the browser will take to tackle the form when it
is submitted. Here, we have taken no action.
o The method to take action can be either post or get, which is used when the form is
to be submitted to the server. Both types of methods have their own properties and
rules.
o The input type tag defines the type of inputs we want to create in our form. Here, we
have used input type as 'text', which means we will input values as text in the textbox.
o Net, we have taken input type as 'password' and the input value will be password.
Other than action and methods, there are the following useful methods also which
are provided by the HTML Form Element
AD
Referencing forms
Now, we have created the form element using HTML, but we also need to make its
connectivity to JavaScript. For this, we use the getElementById() method that
references the html form element to the JavaScript code.
1. let form = document.getElementById('subscribe');
1. <input type="submit" value="Subscribe">
When we submit the form, the action is taken just before the request is sent to the
server. It allows us to add an event listener that enables us to place various
validations on the form. Finally, the form gets ready with a combination of HTML and
JavaScript code.
Let's collect and use all these to create a Login form and SignUp form and use
both.
Login Form
<html>
<head>
<title> Login Form</title>
</head>
</html>
The output of the above code on clicking on Login button is shown below:
<head>
<title> SignUp Page</title>
</head>
<body align="center">
<h1> CREATE YOUR ACCOUNT</h1>
<table cellspacing="2" align="center" cellpadding="8"
border="0">
<tr>
<td> Name</td>
<td><input type="text" placeholder="Enter your
name" id="n1"></td>
</tr>
<tr>
<td>Email </td>
<td><input type="text" placeholder="Enter your
email id" id="e1"></td>
</tr <tr>
<td> Set Password</td>
<td><input type="password" placeholder="Set a
password" id="p1"></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" placeholder="Confirm
your password" id="p2"></td>
</tr>
<tr>
<td>
<input type="submit" value="Create"
onClick="create_account()" />
</table>
<script type="text/javascript">
function create_account() {
var n = document.getElementById("n1").value;
var e = document.getElementById("e1").value;
var p = document.getElementById("p1").value;
var cp = document.getElementById("p2").value;
//Code for password validation
</html>
So, let's see how we can check and uncheck all the checkboxes in a JavaScript code.
<html>
<head>
<title>Selecting or deselecting all CheckBoxes</title>
<script type="text/javascript">
function selects() {
var ele = document.getElementsByName('chk');
for (var i = 0; i < ele.length; i++) {
if (ele[i].type == 'checkbox')
ele[i].checked = true;
}
}
function deSelect() {
var ele = document.getElementsByName('chk');
for (var i = 0; i < ele.length; i++) {
if (ele[i].type == 'checkbox')
ele[i].checked = false;
}
}
</script>
</head>
<body>
<h3>Select or Deselect all or some checkboxes as per
your mood:</h3>
<input type="checkbox" name="chk"
value="Smile">Smile<br>
</html>
Output:
The user can create many such examples of using checkboxes and try out such
function.
So, in this way the user can select all or deselect all checkboxes.
Adding options
There are multiple ways to create an option dynamically and add it to a <select> in
JavaScript.
First, use the Option constructor to create a new option with the specified option text
and value:
The add() method accepts two arguments. The first argument is the new option and
the second one is an existing option.
Second, add the new option to the select element using the appendChild() method:
There are also multiple ways to dynamically remove options from a select element.
select.remove(0);
Code language: CSS (css)
The second way to remove an option is to reference the option by its index using
the options collection and set its value to null:
select.options[0] = null;
Code language: JavaScript (javascript)
The third way is to use the removeChild() method and remove a specified option. The
following code removes the first element of a the selectBox:
To remove all options of a select element, you use the following code:
function removeAll(selectBox) {
while (selectBox.options.length > 0) {
select.remove(0);
}
}
Code language: JavaScript (javascript)
We’ll build a application that allows users to add a new option from the value of an
input text and remove one or more selected options.
├── css
| └── style.css
├── js
| └── app.js
└── index.html
The index.html:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Selected Value</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div id="container">
<form>
<label for="framework">Framework:</label>
<input type="text" id="framework"
placeholder="Enter a framework" autocomplete="off">
<button id="btnAdd">Add</button>
</select>
<button id="btnRemove">Remove Selected
Framework</button>
</html>
Code language: HTML
js/app.js
How it works:
First, use the querySelector() method to select elements including the input text, button,
and selection box:
If the value of the input text is blank, we show an alert to inform the users that the
name is required. Otherwise, we create a new option and add it to the selection box.
After adding the option, we reset the entered text of the input text and set the focus
to it.
https://rahultamkhane.medium.com/develop-a-webpage-using-intrinsic-java-functions-
36cb3b84826c#:~:text=Intrinsic%20JavaScript%20Functions,call%20%E2%80%9Cbuilt
%2Din%E2%80%9D.
1. Number
2. String
3. RegExp
4. Array
5. Math
6. Date
7. Boolean
isNaN()
eval()
Number()
String()
parseInt()
parseFloat()
onclick="javascript:document.forms.contact.submit()"/>
<img src="reset.jpg"
onclick="javascript:document.forms.contact.reset()"/>
</P>
</FORM>
</body>
</html>
Output
Sample Program
if(typeof(pos) == "undefined") {
pos = 0;
}
if(typeof(ins_string) == "undefined") {
ins_string = '';
}
return main_string.slice(0, pos) + ins_string +
main_string.slice(pos);
}
var main_string = "Welcome to JavaScript";
var ins_string = " the world of ";
var pos = 10;
var final_string = insert(main_string, ins_string, pos);
document.write("Main String: <b>" + main_string + "</b><br/>");
document.write("String to insert: <b>" + ins_string +
"</b><br/>");
document.write("Position of string: <b>" + pos + "</b><br/>");
document.write("Final string: <b>" + final_string + "</b>");
</script>
</body>
</html>