0% found this document useful (0 votes)
48 views

CH 3 - Lecture Notes

The document describes a unit of instruction on forms and event handling in HTML. It will cover the basic building blocks of forms like buttons, text boxes, checkboxes and selects. It will also cover form events like mouse and key events. Students will learn how to dynamically change form attributes and options lists using JavaScript. They will also learn how to evaluate checkbox selections, change labels dynamically, and manipulate form elements. The document lists intrinsic JavaScript functions for disabling and making elements read only.

Uploaded by

1234567890
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

CH 3 - Lecture Notes

The document describes a unit of instruction on forms and event handling in HTML. It will cover the basic building blocks of forms like buttons, text boxes, checkboxes and selects. It will also cover form events like mouse and key events. Students will learn how to dynamically change form attributes and options lists using JavaScript. They will also learn how to evaluate checkbox selections, change labels dynamically, and manipulate form elements. The document lists intrinsic JavaScript functions for disabling and making elements read only.

Uploaded by

1234567890
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

3.

UNIT III – Forms and Event Handling – 6 hours


3.1. Building blocks of a Form, properties and methods of form,
button, text, text-area, checkbox, radio button, select element.
3.2. Form events- mouse event, key events.
3.3. Form objects and elements.
3.4. Changing attribute value dynamically.
3.5. Changing option list dynamically
3.6. Evaluating checkbox selection
3.7. Changing a label dynamically
3.8. Manipulating form elements
3.9. Intrinsic JavaScript functions, disabling elements, read only
elements.

https://learn-the-web.algonquindesign.ca/topics/forms-cheat-sheet/#input-types

HTML Forms Revision Tags :


 <form method="post" action="…">
o Tag that wraps around all the form elements.
o action points to where the data should be submitted.
 <fieldset>
o Used to group elements together, like radio buttons.
o Must always have a legend.
 <legend>
o Adds a title to the fieldset.
o Must be inside a fieldset.
 <button type="submit">
o Every form needs a button.
 <label for="…">
o Adds a name to any field.
o Every field must have a label.
 <input id="…" type="…">
o Adds an input field of varying types.
o Must always have an  id to associate a label.
o The type="…" attribute defaults to text.
 <textarea id="…">
o Adds a large, multi-line text field.
o Must always have an  id to associate a label.
 <select id="…">
o Creates a drop-down choice input.
o Populate the choices with <option> tags.
o Must always have an  id to associate a label.
 <datalist id="…">
o Creates a list of items for autocompletion.
o Populate the choices with <option> tags.
o Won’t be visible until the associated field is typed into.
 <option>
o Creates an entry inside <select> or <datalist>.
o Use the selected attribute to set a default value.
o For select: <option>Triceratops</option>
o For datalist: <option value="Pteranodon">

Notes Prepared by - Chandan Somani | 


 <optgroup label="…">
o Creates a group of options inside a <select>.
o label="…" is used as a visible name for the group.
 <output for="…">
o Represents the result of a calculation performed by JavaScript.
o for="…" is a space-separate list of input ids that contributed to the calculation.
Input types
 text default
o Single line text field.
o If you want, you can leave type="text" off the input.
 number
o Accepts numbers; has a up/down switch.
 email
o Accepts valid email addresses.
 tel
o For telephone numbers.
o There is no restricted format to accommodate all different countries.
 url
o Accepts a valid website URL.
 password
o For passwords; hides typed characters.
 time
o For accepting time: hours, minutes, seconds.
 date
o For accepting dates; shows a calendar picker.
 datetime-local
o For accepting a both a date and a time; shows a calendar & time picker.
 week
o For accepting a specific week; likely shows a calendar picker.
 month
o For accepting a specific month; likely shows a calendar picker.
 color
o For picking a specific colour; shows a colour palette.
o Outputs as a hex colour.
 range
o For selecting from a range of numbers.
 file
o For choosing a file to upload.
o Use accept="…" to limit filetypes.
o <input type="file" accept=".jpg,.png,.gif" id="photo">
 search
o Specifies the input as a search field.
 checkbox
o Turns the input into a check toggle.
 radio
o Turns the input into a radio button.
o All radio buttons in the group should have the same name="…"
 hidden
o Makes the input field invisible.
Input attributes
Some of these attributes also apply to select and textarea.

 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="…"

Notes Prepared by - Chandan Somani | 


o Adds a temporary, helpful hint into the field.
o <input type="email" placeholder="[email protected]" id="email">
o Do not use this as a replacement for <label>
 autocomplete="off"
o Disable auto completion in the field.
 autocapitalize="none"
o Disable auto capitalization in the field.
o Non-standard: only works in iOS.
 inputmode="…"
o Hint the browser to display a specific keyboard.
o verbatim, numeric, etc.
 list="…"
o The id of an associated <datalist>
 maxlength="…"
o For setting a maximum number of characters.
o <input type="email" maxlength="256" id="email">
 minlength="…"
o For setting a minimum number of characters.
o <input type="text" minlength="6" id="postal-code">
 min="…"
o Sets a minimum numerical value on range & number.
o <input type="number" min="5" id="dino">
 max="…"
o Sets a maximum numerical value on range & number.
o <input type="range" max="100" id="dino">
 step="…"
o Controls how the number will increment in range & number.
o <input type="number" step="0.1" id="dino">
 pattern="…"
o A JavaScript regular expression to control what is valid input.
o <input type="text" pattern="[A-Za-z][0-9][A-Za-z] ?[0-9][A-Za-z][0-9]" id="postal-
code">
 multiple
o For allowing multiple entries in the field.
o Works for: <select>, email, file
 spellcheck
o Trigger the browser to perform spell checking in the field.
 readonly
o Stops the user from modifying the value of the field.
 disabled
o Stops any interaction on the field.
 autofocus
o When the page loads, this field will be focused.
o Be really careful, only use this when the whole purpose of the page is to fill the form.
Examples
 Simple form
o <form method="post" action="//formspree.io/[email protected]">
o <label for="email">Email address</label>
o <input type="email" id="email" required>
o <button type="submit">Sign up!</button>
o </form>

 Radio button group


o <fieldset>
o <legend>Favourite dinosaur</legend>
o <input type="radio" id="trex" name="dinos">
o <label for="trex">T. rex</label>
o <input type="radio" id="tri" name="dinos">
o <label for="tri">Triceratops</label>
o <input type="radio" id="stego" name="dinos">
o <label for="stego">Stegosaurus</label>
o </fieldset>

Notes Prepared by - Chandan Somani | 


 Autocomplete field
o <label for="province">Province</label>
o <input id="province" list="province-list" required>
o <datalist id="province-list">
o <option value="Alberta">
o <option value="Ontario">
o <option value="Québec">
o <option value="Nova Scotia">
o </datalist>

Some good Cheat Sheets


https://www.december.com/html/spec/HTML5-Cheat-Sheet.pdf [18 pages]
https://web.stanford.edu/group/csp/cs21/htmlcheatsheet.pdf [2 pages]
https://htmlcheatsheet.com/ [Web version]

FOR JavaScript
https://htmlcheatsheet.com/js/

Notes Prepared by - Chandan Somani | 


What is an Event?
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an
event. Other examples include events like pressing any key, closing a window, resizing a
window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons
to close windows, messages to be displayed to users, data to be validated, and virtually any
other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here
we will see a few examples to understand a relation between Event and JavaScript −

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.
Example
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<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.

Notes Prepared by - Chandan Somani | 


Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>

<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the
following example.
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>

<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.

Notes Prepared by - Chandan Somani | 


Attribute Value Description
onblur script Triggers when the window loses focus
onchange script Triggers when an element changes
onclick script Triggers on a mouse click
ondblclick script Triggers on a mouse double-click
ondrag script Triggers when an element is dragged
onfocus script Triggers when the window gets focus
onformchange script Triggers when a form changes
onforminput script Triggers when a form gets user input
onkeydown script Triggers when a key is pressed
onkeypress script Triggers when a key is pressed and released
onkeyup script Triggers when a key is released
onload script Triggers when the document loads
onmousedown script Triggers when a mouse button is pressed
onmousemove script Triggers when the mouse pointer moves
onmouseout script Triggers when the mouse pointer moves out of an element
onmouseover script Triggers when the mouse pointer moves over an element
onmouseup script Triggers when a mouse button is released
onsubmit script Triggers when a form is submitted

https://www.infoworld.com/article/2077176/using-javascript-and-forms.html

Using JavaScript and forms


Javascript wears many hats. You can use JavaScript to create special effects. You can use
JavaScript to make your HTML pages "smarter" by exploiting its decision-making
capabilities. And you can use JavaScript to enhance HTML forms. This last application is of
particular importance. Of all the hats JavaScript can wear, its form processing features are
among the most sought and used.

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.

Notes Prepared by - Chandan Somani | 


Creating the form
There are few differences between a straight HTML form and a JavaScript-enhanced form.
The main one being that a JavaScript form relies on one or more event handlers, such as
onClick or onSubmit. These invoke a JavaScript action when the user does something in the
form, like clicking a button. The event handlers, which are placed with the rest of the
attributes in the HTML form tags, are invisible to a browser that don't support JavaScript.
Because of this trait, you can often use one form for both JavaScript and non-JavaScript
browsers.

Typical form control objects -- also called "widgets" -- include the following:

 Text box for entering a line of text


 Push button for selecting an action
 Radio buttons for making one selection among a group of options
 Check boxes for selecting or deselecting a single, independent option

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" ACTION="" METHOD="GET">


Enter something in the box: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Click"
onClick="testResults(this.form)">
</FORM>

 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.

Getting a value from a form object


Let's experiment with obtaining values from form objects. Load the page, then type
something into the text box. Click the button, and what you typed is shown in the alert box.

Listing 1. testform.html

<HTML>

Notes Prepared by - Chandan Somani | 


<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var TestVar = form.inputbox.value;
alert ("You typed: " + TestVar);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in
the box: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Click"
onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
Here's how the script works. JavaScript calls the testResults function when you click the
button in the form. The testResults function is passed the form object using the
syntax this.form (the this keyword references the button control; form is a property of the
button control and represents the form object). I've given the form object the
name form inside the testResult function, but you can any name you like.

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).

Setting a value in a form object


The value property of the inputbox, shown in the above example, is both readable and
writable. That is, you can read whatever is typed into the box, and you can write data back
into it. The process of setting the value in a form object is just the reverse of reading it. Here's
a short example to demonstrate setting a value in a form text box. The process is similar to
the previous example, except this time there are two buttons. Click the "Read" button and the
script reads what you typed into the text box. Click the "Write" button and the script writes a
particularly lurid phrase into the text box.

Listing 2. set_formval.html

<HTML>
<HEAD>
<TITLE>Test Input </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function readText (form) {
TestVar =form.inputbox.value;

Notes Prepared by - Chandan Somani | 


alert ("You typed: " + TestVar);
}
function writeText (form) {
form.inputbox.value = "Have a nice day!"
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">
Enter something in the box: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button1" Value="Read" onClick="readText(this.form)">
<INPUT TYPE="button" NAME="button2" Value="Write"
onClick="writeText(this.form)">
</FORM>
</BODY>
</HTML>

 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.

Reading other form object values


The text box is perhaps the most common form object you'll read (or write) using JavaScript.
However, you can use JavaScript to read and write values from most other objects (note that
JavaScript cannot currently be used to read or write data using the password text box). In
addition to text boxes, JavaScript can be used with:

 Hidden text box (TYPE="hidden").


 Radio button (TYPE="radio")
 Check box (TYPE="checkbox")
 Text area (<TEXT AREA>)
 Lists (<SELECT>)

Using Hidden Text Boxes


From a JavaScript standpoint, hidden text boxes behave just like regular text boxes, sharing
the same properties and methods. From a user standpoint, hidden text boxes "don't exist"
because they do not appear in the form. Rather, hidden text boxes are the means by which
special information can be passed between server and client. They can also be used to hold
temporary data that you might want to use later. Because hidden text boxes are used like
standard text boxes a separate example won't be provided here.

Using Radio Buttons


Radio buttons are used to allow the user to select one, and only one, item from a group of
options. Radio buttons are always used in multiples; there is no logical sense in having just
one radio button on a form, because once you click on it, you can't unclick it. If you want a
simple click/unclick choice use a check box instead (see below).

Notes Prepared by - Chandan Somani | 


To define radio buttons for JavaScript, provide each object with the same name. JavaScript
will create an array using the name you've provided; you then reference the buttons using the
array indexes. The first button in the series is numbered 0, the second is numbered 1, and so
forth. Note that the VALUE attribute is optional for JavaScript-only forms. You'll want to
provide a value if you submit the form to a CGI program running on the server, however.

<INPUT TYPE="radio" NAME="rad" VALUE="radio_button1" onClick=0>


<INPUT TYPE="radio" NAME="rad" VALUE="radio_button2" onClick=0>
<INPUT TYPE="radio" NAME="rad" VALUE="radio_button3" onClick=0>
<INPUT TYPE="radio" NAME="rad" VALUE="radio_button4" onClick=0>

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:

<INPUT TYPE="radio" NAME="rad" Value="rad_button1" CHECKED onClick=0>

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.

form.rad[0].checked = true; // sets to first button in the rad group

Using Check Boxes


Check boxes are stand-alone elements; that is, they don't interact with neighboring elements
like radio buttons do. Therefore they are a bit easier to use. Using JavaScript you can test if a
check box is checked using the checked property, as shown here. Likewise, you can set the
checked property to add or remove the checkmark from a check box. In this example an alert

Notes Prepared by - Chandan Somani | 


message tells you if the first check box is checked. The value is true if the box is checked;
false if it is not.

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.

<INPUT TYPE="checkbox" NAME="check1" Value="0" CHECKED>Checkbox 1>

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;

Using Text Areas

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:

<TEXTAREA NAME="myarea" COLS="40" ROWS="7">


</TEXTAREA>
You can use JavaScript to read the contents of the text area box. This is done with the value
property. Here is an example:

Listing 5. form_textarea.html
<HTML>

<HEAD>
    <TITLE>Text Area Test</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
        function seeTextArea(form) {
            alert(form.myarea.value);
        }
    </SCRIPT>
</HEAD>

Notes Prepared by - Chandan Somani | 


<BODY>
    <FORM NAME="myform">
        <INPUT TYPE="button" NAME="button3" Value="Test"
onClick="seeTextArea(this.form)">
        <TEXTAREA NAME="myarea" COLS="40" ROWS="5">
    </TEXTAREA>
    </FORM>
</BODY>

</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:

form.textarea.value = "Text goes here";

 form is the name of the form.


 textarea is the name of the textarea.
 "Text goes here" is the text you want to display

Using Selection Lists


List boxes let you pick the item you want out of a multiple-choice box. The listbox itself is
created with the <SELECT> tag, and the items inside it are created by one or more
<OPTION> tags. You can have any number of <OPTION> tags in a list. The list is
terminated with a </SELECT> tag.

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>

Notes Prepared by - Chandan Somani | 


</HEAD>

<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:

    function testSelect (form) {


    Item = form.list.selectedIndex;
    Result = form.list.options[Item].text;
    alert (Result);
}
Other events you can trigger within a form
I've used the onClick event handler in all of the examples because that's the one you are most
likely to deal with in your forms. Yet JavaScript supports a number of other event handlers as
well. Use these as the need arises, and the mood fits. In Navigator 2.x The event handlers
used with form object are:

 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).

Submitting the form to the server


In the examples above I've limited the action of the form to within JavaScript only. Many
forms are designed to send data back to a CGI program runnong on the server. This is
referred to as submitting the form, and is accomplished using either of two JavaScript
instructions: the onSubmit event handler or the submit method. In most instances, you use
one or the other, not both!

 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").

Notes Prepared by - Chandan Somani | 


 Place the submit instruction anywhere in your JavaScript. It can be activated by any action,
such as clicking a form button that has been defined with the onClick event handler.

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>

Notes Prepared by - Chandan Somani | 


</HTML>

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>

Notes Prepared by - Chandan Somani | 


</BODY>

</HTML>

Validating form data using JavaScript


The World Wide Web "grew up" when they added the ability to display forms. In the days
before forms, the Web was only mildly interactive, with just hypertext links to take readers
from location to location. Forms allow users to truly interact with the Web. For example,
readers can specify search queries using a simple one-line text box.

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) {

Notes Prepared by - Chandan Somani | 


            if (InString.length == 0) return (false);
            var RefString = "1234567890";
            for (Count = 0; Count < InString.length; Count+
+) {
                TempChar = InString.substring(Count, Count +
1);
                if (RefString.indexOf(TempChar, 0) == -1)
                    return (false);
            }
            return (true);
        }
    </SCRIPT>
</HEAD>

<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.

Notes Prepared by - Chandan Somani | 


JavaScript Form
In this tutorial, we will learn, discuss, and understand the JavaScript form. We will also
see the implementation of the JavaScript form for different purposes.

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.

Notes Prepared by - Chandan Somani | 


o Next, we have taken input type as 'button' where on clicking, we get the value of the
form and get displayed.

Other than action and methods, there are the following useful methods also which
are provided by the HTML Form Element

o submit (): The method is used to submit the form.


o reset (): The method is used to reset the form values.

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.

The syntax of using the getElementById() method is as follows:

1. let form = document.getElementById('subscribe');  

Using the Id, we can make the reference.

Submitting the form


Next, we need to submit the form by submitting its value, for which we use
the onSubmit() method. Generally, to submit, we use a submit button that submits
the value entered in the form.

The syntax of the submit() method is as follows:

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>

Notes Prepared by - Chandan Somani | 


<body>
    <h3> LOGIN </h3>
    <form name="Login_form" onsubmit="submit_form()">
        <h4> USERNAME</h4>
        <input type="text" placeholder="Enter your email id"
/>
        <h4> PASSWORD</h4>
        <input type="password" placeholder="Enter your
password" /></br></br>
        <input type="submit" value="Login" />
        <input type="button" value="SignUp"
onClick="create()" />
    </form>
    <script type="text/javascript">
        function submit_form() {
            alert("Login successfully");
        }
        function create() {
            window.location = "signup.html";
        }  
    </script>
</body>

</html>

The output of the above code on clicking on Login button is shown below:

Notes Prepared by - Chandan Somani | 


SignUp Form
<html>

<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  

Notes Prepared by - Chandan Somani | 


            var letters = /^[A-Za-z]+$/;
            var email_val = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-
Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            //other validations required code  
            if (n == '' || e == '' || p == '' || cp == '') {
                alert("Enter each details correctly");
            }
            else if (!letters.test(n)) {
                alert('Name is incorrect must contain
alphabets only');
            }
            else if (!email_val.test(e)) {
                alert('Invalid email format please enter
valid email id');
            }
            else if (p != cp) {
                alert("Passwords not matching");
            }
            else if
(document.getElementById("p1").value.length > 12) {
                alert("Password maximum length is 12");
            }
            else if
(document.getElementById("p1").value.length < 6) {
                alert("Password minimum length is 6");
            }
            else {
                alert("Your account has been created
successfully... Redirecting to JavaTpoint.com");
                window.location =
"https://www.javatpoint.com/";
            }
        }  
    </script>
</body>

</html>

The output of the above code is shown below:

Notes Prepared by - Chandan Somani | 


In this way, we can create forms in JavaScript with proper validations.

Notes Prepared by - Chandan Somani | 


https://www.javatpoint.com/how-to-select-all-checkboxes-using-javascript

How to select all checkboxes using


JavaScript
In order to select all the checkboxes of a page, we need to create a selectAll ()
function through which we can select all the checkboxes together. In this section, not
only we will learn to select all checkboxes, but we will also create another function
that will deselect all the checked checkboxes.

So, let's see how we can check and uncheck all the checkboxes in a JavaScript code.

Selecting all checkboxes in a JavaScript code


We will implement and understand an example where we will create two buttons one
for selecting all checkboxes and the other one for deselecting all the selected
checkoxes. The example code is given below:

<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>

Notes Prepared by - Chandan Somani | 


    <input type="checkbox" name="chk" value="Cry">Cry<br>
    <input type="checkbox" name="chk"
value="Laugh">Laugh<br>
    <input type="checkbox" name="chk"
value="Angry">Angry<br>
    <br>
    <input type="button" onclick='selects()' value="Select
All" />
    <input type="button" onclick='deSelect()'
value="Deselect All" />
</body>

</html>

Output:

When we click on the 'Select All' button, we get:

When we deselect all checkboxes, we get:

Notes Prepared by - Chandan Somani | 


Code Explanation

1. The above complete code is based on HTML and JavaScript.


2. In the html body section, we have created four input types as Checkboxes and two
more input types as button. For the input types as button, we have created one
button for selecting the checkboxes where onClick (), the selects () function will be
invoked and the other one for deselecting the checkboxes (if selected any/all) where
onClick () the deselect () function will be invoked.
3. So, when the user clicks on the 'Select All' button, it moves to the script section where
it finds the selects () function and executes the statements within it.
4. Similarly, when the user after selecting the checkboxes click on the "Deselect All"
button, the deselect () function gets invoked. Also, if the user has selected a single or
two checkboxes only, then also on clicking on the "Deselect All" button, it will
deselect them. In case the user has not selected any checkbox and then clicking on
the "Deselect All" button, no action will be shown or performed.

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.

Notes Prepared by - Chandan Somani | 


https://www.javascripttutorial.net/javascript-dom/javascript-add-remove-options/

JavaScript: Dynamically Add & Remove Options


Summary: in this tutorial, you will learn how to dynamically add options to and
remove options from a select element in JavaScript.

The HTMLSelectElement type represents the <select> element. It has the add() method that


dynamically adds an option to the <select> element and the remove() method that
removes an option from the <select> element:

 add(option,existingOption) – adds a new <option> element to the <select> before an


existing option.
 remove(index) – removes an option specified by the index from a <select>.

Adding options

To add an option dynamically to a <select> element, you use these steps:

 First, create a new option.


 Second, add the option to the select element.

There are multiple ways to create an option dynamically and add it to a <select> in
JavaScript.

1) Using the Option constructor and add() method

First, use the Option constructor to create a new option with the specified option text
and value:

let newOption = new Option('Option Text','Option Value');


Code language: JavaScript (javascript)

Then, call the add() method of the HTMLSelectElement element:

const select = document.querySelector('select');


select.add(newOption,undefined);
Code language: JavaScript (javascript)

The add() method accepts two arguments. The first argument is the new option and
the second one is an existing option.

In this example, we pass undefined in the second argument, the method add() method


will add the new option to the end of the options list.

2) Using the DOM methods

First, construct a new option using DOM methods:

Notes Prepared by - Chandan Somani | 


// create option using DOM
const newOption = document.createElement('option');
const optionText = document.createTextNode('Option Text');
// set option text
newOption.appendChild(optionText);
// and option value
newOption.setAttribute('value','Option Value');
Code language: JavaScript (javascript)

Second, add the new option to the select element using the appendChild() method:

const select = document.querySelector('select');


select.appendChild(newOption);
Code language: JavaScript (javascript)
Removing Options

There are also multiple ways to dynamically remove options from a select element.

The first way is to use the remove() method of the HTMLSelectElement type. The following 


illustrates how to remove the first option:

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:

// remove the first element:


select.removeChild(selectBox.options[0]);
Code language: JavaScript (javascript)

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)

Notes Prepared by - Chandan Somani | 


When you remove the first option, the select element moves another option as the
first option. The removeAll() function repeatedly removes the first option in the select
element, therefore, it removes all the options.

Put it all together

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.

Here’s the project’s structure:

├── 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>

                <label for="list">Framework List:</label>


                <select id="list" name="list" multiple>

                </select>
                <button id="btnRemove">Remove Selected
Framework</button>

Notes Prepared by - Chandan Somani | 


            </form>
        </div>
        <script src="js/app.js"></script>
    </body>

</html>
Code language: HTML

js/app.js

const btnAdd = document.querySelector('#btnAdd');


const btnRemove = document.querySelector('#btnRemove');
const listbox = document.querySelector('#list');
const framework = document.querySelector('#framework');

btnAdd.onclick = (e) => {


  e.preventDefault();

  // validate the option


  if (framework.value == '') {
    alert('Please enter the name.');
    return;
  }
  // create a new option
  const option = new Option(framework.value,
framework.value);
  // add it to the list
  listbox.add(option, undefined);

  // reset the value of the input


  framework.value = '';
  framework.focus();
};

// remove selected option


btnRemove.onclick = (e) => {
  e.preventDefault();

  // save the selected options


  let selected = [];

  for (let i = 0; i < listbox.options.length; i++) {


    selected[i] = listbox.options[i].selected;

Notes Prepared by - Chandan Somani | 


  }

  // remove all selected option


  let index = listbox.options.length;
  while (index--) {
    if (selected[index]) {
      listbox.remove(index);
    }
  }
};
Code language: JavaScript (javascript)

The style can be found here.

How it works:

First, use the querySelector() method to select elements including the input text, button,
and selection box:

const btnAdd = document.querySelector('#btnAdd');


const btnRemove = document.querySelector('#btnRemove');
const listbox = document.querySelector('#list');
const framework = document.querySelector('#framework');
Code language: JavaScript (javascript)

Second, attach the click event listener to the btnAdd button.

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.

btnAdd.addEventListener('click', (e) => {


  e.preventDefault();

  // validate the option


  if (framework.value.trim() === '') {
    alert('Please enter the name.');
    return;
  }
  // create a new option
  const option = new Option(framework.value,
framework.value);

  // add it to the list

Notes Prepared by - Chandan Somani | 


  listbox.add(option, undefined);

  // reset the value of the input


  framework.value = '';
  framework.focus();
});
Code language: JavaScript (javascript)

Third, register a click event listener to the btnRemove button. In the event listener, we


save the selected options in an array and remove each of them.

btnRemove.addEventListener('click', (e) => {


  e.preventDefault();

  // save the selected options


  let selected = [];

  for (let i = 0; i < listbox.options.length; i++) {


    selected[i] = listbox.options[i].selected;
  }

  // remove all selected option


  let index = listbox.options.length;
  while (index--) {
    if (selected[index]) {
      listbox.remove(index);
    }
  }
});
Code language: JavaScript (javascript)
Summary

 JavaScript uses the HTMLSelectElement type to represent the <select> element.


 Use the add() method of the HTMLSelectElement to add an option to
the <select> element.
 Use the remove() method of the HTMLSelectElement to remove an option from
the <select> element.

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.

Notes Prepared by - Chandan Somani | 


https://rahultamkhane.medium.com/create-a-webpage-to-implement-form-events-part-i-
92bca59b1c73
https://rahultamkhane.medium.com/create-a-webpage-to-implement-form-events-part-ii-
16e520130027

Intrinsic JavaScript Functions


 An intrinsic function (or built-in function) is a
function (subroutine) available for use in a given
programming language whose implementation is handled
specially by the compiler.
 “Intrinsic” is the way some authors refer to what other
authors call “built-in”.
 Those data types/objects/classes are always there
regardless of what environment you’re running in.
 JavaScript provides intrinsic (or “built-in”) objects. They
are the Array, Boolean, Date, Error, Function, Global,
JSON, Math, Number, Object, RegExp, and String objects.
 As you know JavaScript is an object oriented programming
language, it supports the concept of objects in the form of
attributes.
 If an object attribute consists of function, then it is a
method of that object, or if an object attribute consists of
values, then it is a property of that object.
 For example,
var status = document.readyState;

readyState is a property of the document object which can contain


values such as “unintialized”, ”loading”, ”interactive”, ”complete”
whereas,
document.write("Hello World");

write() is a method of the document object that writes the content


“Hello World” on the web page.

Notes Prepared by - Chandan Somani | 


 JavaScript Built-in objects such as

1. Number
2. String
3. RegExp
4. Array
5. Math
6. Date
7. Boolean

 Each of the above objects hold several built-in functions to


perform object related functionality.

isNaN()

 isNaN() method determines whether value of a variable is


a legal number or not.
 For example
document.write(isNan(0)); // false
document.write(isNan('JavaScript')); // true

eval()

 eval() is used to execute Javascript source code.


 It evaluates or executes the argument passed to it and
generates output.
 For example
eval("var
number=2;number=number+2;document.write(number)"); //4

Number()

 Number() method takes an object as an argument and


converts it to the corresponding number value.
 Return Nan (Not a Number) if the object passed cannot be
converted to a number
 For example

Notes Prepared by - Chandan Somani | 


var obj1=new String("123");
var obj2=new Boolean("false");
var obj3=new Boolean("true");
var obj4=new Date();
var obj5=new String("9191 9999");document.write(Number(obj1));
// 123
document.write(Number(obj2)); // 0
document.write(Number(obj3)); // 1
document.write(Number(obj4)); // 1342720050291
document.write(Number(obj5)); // NaN

String()

 String() function converts the object argument passed to it


to a string value.
 For example
document.write(new Boolean(0)); // false
document.write(new Boolean(1)); // true
document.write(new Date()); // Tue Jan 05 2021 13:28:00
GMT+0530

parseInt()

 parseInt() function takes string as a parameter and


converts it to integer.
 For example
document.write(parseInt("45")); // 45
document.write(parseInt("85 days")); // 85
document.write(parseInt("this is 9")); // NaN

 An optional radix parameter can also be used to specify the


number system to be used to parse the string argument.
 For example,
document.write(parseInt(“10”,16)); //16

parseFloat()

 parseFloat() function takes a string as parameter and


parses it to a floating point number.
 For example
document.write(parseFloat("15.26")); // 15.26
document.write(parseFloat("15 48 65")); // 15
document.write(parseFloat("this is 29")); // NaN
document.write(pareFloat(" 54 ")); // 54

Notes Prepared by - Chandan Somani | 


 An intrinsic function is often used to replace the Submit
button and the Reset button with your own graphical
images, which are displayed on a form in place of these
buttons.
<html>
<head>
<title>Using Intrinsic JavaScript Functions</title>
</head>
<body>
<FORM name="contact" action="#" method="post">
<P>
First Name: <INPUT type="text" name="Fname"/> <BR>
Last Name: <INPUT type="text" name="Lname"/><BR>
Email: <INPUT type="text" name="Email"/><BR>
<img src="submit.jpg"

onclick="javascript:document.forms.contact.submit()"/>
<img src="reset.jpg"

onclick="javascript:document.forms.contact.reset()"/>
</P>
</FORM>
</body>
</html>

Output

Sample Program

Write a JavaScript function to insert a string within a


string at a particular position (default is 1).
<html><head>
<title>Insert a string within a specific position in another
string</title>
</head><body>

Notes Prepared by - Chandan Somani | 


<script>
function insert(main_string, ins_string, pos) {

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>

Output: Insert string in middle

Notes Prepared by - Chandan Somani | 

You might also like