1_
How to run code when form gets loaded
JavaScript
function initialize()
{
// do something
}
HTML <body onload="initialize()">
2_
Write to HTML
JavaScript
function doSomething()
{
document.write("Hello");
}
3_
Get value of edit box and DIV html
DOM elements can be accessed like below
HTML <input id="edit1" type="text" value="abc" />
JavaScript
var label = document.getElementById("myId");
var edit = document.getElementById("edit1");
alert(
"Text value is: " + label.innerHTML +
", Edit box value is: " + edit.value
);
edit.disabled=true; // disable edit box
4_
How to validate form
JavaScript
function validateForm()
{
var result = ....
return result;
}
HTML <FORM action="form_response.htm" method="post" onSubmit="return validateForm()" > ... </FORM>
5_
Respond to changing values in form controls
Edit box will trigger that event only when it loses focus.
HTML
<select name="comboOptions" onchange="alert('You selected ' + this.value)">
...
</select>
6_
Setting visibility of elements
JavaScript
if (shouldBeHidden) {
document.getElementById("myId").style.display = "none";
}else {
document.getElementById("myId").style.display = "block";
}
7_
Make AJAX call
AJAX stands for "Asynchronous Javascript And Xml". It allows updating parts of web page without reloading the whole page.
JavaScript
function onClick() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
// IE 5,6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("lblHello").innerText = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://localhost/ajax.txt", true);
xmlhttp.send();
}
HTML <div id="lblHello">will be updated with AJAX</div> <input id="btnGet" type="button" value="Make AJAX call" onclick="onClick()"/>
8_
Create object
JavaScript
var person = {
firstName: "John",
lastName: "First"
};
alert(person.firstName);
9_
Create object using function
JavaScript
function Person() {
this.firstName = "John";
this.lastName = "First";
}
var p = new Person();
10_
One and two way data binding with Knockout
HTML
<html>
<head>
<script type='text/javascript' src="knockout-3.1.0.debug.js"></script>
</head>
<body>
First name: <span data-bind="text: firstName"></span><br/>
Last name: <input data-bind="value: lastName" /><br/>
<button onclick="alert(_viewModel.firstName)">Show First name</button><br/>
<button onclick="alert(_viewModel.lastName())">Show Last name</button>
<script>
var _viewModel = {
firstName: "John",
lastName: ko.observable("First")
};
ko.applyBindings(_viewModel);
</script>
</body>
</html>