Solution Is:
<script>
ducument.write(encodeURI(►));
OR
ducument.write(encodeURIComponent(►));
</script>
2. How to write Hello World on the web page?
<script>
document.write("Hello World");
</script>
3. How to loop through array in JavaScript?
There are various way to loop through array in JavaScript.
Generic loop:
<script langugage="javascript">
var i;
for (i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
</script>
ES5's forEach:
<script langugage="javascript">
substr.forEach(function(item) {
// do something with `item`
});
</script>
jQuery.each:
<script langugage="javascript">
jQuery.each(substr, function(index, item) {
// do something with `item` (or `this` is also `item` if you like)
});
</script>
4. What are decodeURI() and encodeURI() functions in JavaScript?
Many characters cannot be sent in a URL, but must be converted to their hex encoding. These functions are used to convert an entire URI (a superset of URL) to and from a format that can be sent via a URI.
<script type="text/javascript">
var uri = "http://www.google.com/search?q=Online Web Tutorials at GlobalGuideLine"
document.write("Original uri: "+uri);
document.write("<br />encoded: "+encodeURI(uri));
</script>
5. What's Prototypes for JavaScript?
Objects have "prototypes" from which they may inherit fields and functions.
<script type="text/javascript">
function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
function movie(title, director) {
this.title = title;
this.director = director || "unknown"; //if null assign to "unknown"
this.toString = movieToString; //assign function to this method pointer
}
movie.prototype.isComedy = false; //add a field to the movie's prototype
var officeSpace = new movie("OfficeSpace");
var narnia = new movie("Narni","Andrew Adamson");
document.write(narnia.toString());
document.write("
Narnia a comedy? "+narnia.isComedy);
officeSpace.isComedy = true; //override the default just for this object
document.write("
Office Space a comedy? "+officeSpace.isComedy);
</script>
6. How to create a function using function constructor?
The following example illustrates this
It creates a function called square with argument x and returns x multiplied by itself.
var square = new Function ("x","return x*x");
7. What does break and continue statements do in JavaScript?
Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop in JavaScript.
8. What is eval() in JavaScript?
The eval() method is incredibly powerful allowing us to execute snippets of code during execution in JavaScript.
<script type="text/javascript">
var USA_Texas_Austin = "521,289";
document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
</script>
This produces
Population is 521,289
9. How to associate functions with objects using JavaScript?
Now create a custom "toString()" method for our movie object. We can embed the function directly in the object like this.
<script type="text/javascript">
function movie(title, director) {
this.title = title;
this.director = director;
this.toString = function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
}
var narnia = new movie("Narni","Andrew Adamson");
document.write(narnia.toString());
</script>
This produces
title: Narni director: Andrew Adamson
Or we can use a previously defined function and assign it to a variable. Note that the name of the function is not followed by parenthisis, otherwise it would just execute the function and stuff the returned value into the variable.
<script type="text/javascript">
function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
function movie(title, director) {
this.title = title;
this.director = director;
this.toString = movieToString;
}
var aliens = new movie("Aliens","Cameron");
document.write(aliens.toString());
</script>
This produces
title: Aliens director: Cameron
10. How to create an object using JavaScript?
Objects can be created in many ways. One way is to create the object and add the fields directly.
<script type="text/javascript">
var myMovie = new Object();
myMovie.title = "Aliens";
myMovie.director = "James Cameron";
document.write("movie: title ""+myMovie.title+""");
<
This produces
movie: title "Aliens"
To create an object write a method with the name of object and invoke the method with "new".
<script type="text/javascript">
function movie(title, director) {
this.title = title;
this.director = director;
}
var aliens = new movie("Aliens","Cameron");
document.write("aliens:"+aliens.toString());
</script>
This produces
aliens:[object Object]
Use an abbreviated format for creating fields using a ":" to separate the name of the field from its value. This is equivalent to the above code using "this.".
<script type="text/javascript">
function movie(title, director) {
title : title;
director : director;
}
var aliens = new movie("Aliens","Cameron");
document.write("aliens:"+aliens.toString());
</script>
This produces
aliens:[object Object]
11. How to shift and unshift using JavaScript?
<script type="text/javascript">
var numbers = ["one", "two", "three", "four"];
numbers.unshift("zero");
document.write(" "+numbers.shift());
document.write(" "+numbers.shift());
document.write(" "+numbers.shift());
</script>
This produces
zero one two
shift, unshift, push, and pop may be used on the same array in JavaScript. Queues are easily implemented using combinations.
12. How to make a array as a stack using JavaScript?
The pop() and push() functions turn a harmless array into a stack in JavaScript...
<script type="text/javascript">
var numbers = ["one", "two", "three", "four"];
numbers.push("five");
numbers.push("six");
document.write(numbers.pop());
document.write(numbers.pop());
document.write(numbers.pop());
</script>
This produces
sixfivefour
13. How to use "join()" to create a string from an array using JavaScript?
"join" concatenates the array elements with a specified separator between them in JavaScript.
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("days:"+days.join(","));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
14. How to use strings as array indexes using JavaScript?
JavaScript does not have a true hashtable object, but through its wierdness, you can use the array as a hashtable.
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
for(var i=0; i < days.length; i++) {
days[days[i]] = days[i];
}
document.write("days["Monday"]:"+days["Monday"]);
</script>
This produces
days["Monday"]:Monday
15. How to delete an array entry using JavaScript?
The "delete" operator removes an array element in JavaScript , but oddly does not change the size of the array.
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("Number of days:"+days.length); delete days[4];
document.write("<br />Number of days:"+days.length);
</script>
This produces
Number of days:7
Number of days:7
16. What does the delete operator do?
The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword.
17. What's the Date object using JavaScript?
Time inside a date object is stored as milliseconds since Jan 1, 1970 in JavaScript.
e.g.
new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)"
new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00"
new Date(06,01,02) - new Date(06,01,01) // produces "86400000"
18. What's Math Constants and Functions using JavaScript?
The Math object contains useful constants such as
Math.PI, Math.E
Math also has a zillion helpful functions in JavaScript.
Math.abs(value); //absolute value
Math.max(value1, value2); //find the largest
Math.random() //generate a decimal number between 0 and 1
Math.floor(Math.random()*101) //generate a decimal number between 0 and 100
19. How to test for bad numbers using JavaScript?
The global method, "isNaN()" can tell us about value if a number has gone bad in JavaScript.
var temperature = parseFloat(myTemperatureWidget.value);
if(!isNaN(temperature)) {
alert("Please enter a valid temperature.");
}
20. How to convert numbers to strings using JavaScript?
We can prepend the number with an empty string in JavaScript
var mystring = ""+myinteger;
//or
var mystring = myinteger.toString();
We can specify a base for the conversion,
var myinteger = 14;
var mystring = myinteger.toString(16);
mystring will be "e".
21. How to convert a string to a number using JavaScript?
We can use the parseInt() and parseFloat() methods in JavaScript to convert a string to a number or numeric value. Notice that extra letters following a valid number are ignored, which is kinda wierd but convenient at times.
parseInt("100") ==> 100
parseFloat("98.6") ==> 98.6
parseFloat("98.6 is a common temperature.") ==> 98.6
parseInt("aa") ==> Nan //Not a Number
parseInt("aa",16) ==> 170 //We can supply a radix or base
22. How to force a page to go to another page using JavaScript?
<script language="JavaScript" type="text/javascript" >
<!--
location.href="http://www.globalguideline.com";
//-->
</script>
23. How to reload the current page?
To reload the current web page using JavaScript use the below line of code...
window.location.reload(true);
24. How to set the cursor to wait?
In theory, we should cache the current state of the cursor and then put it back to its original state.
document.body.style.cursor = 'wait';
//do something interesting and time consuming
document.body.style.cursor = 'auto';
25. How to make elements invisible?
Change the "visibility" attribute of the style object associated with your element. Remember that a hidden element still takes up space, use "display" to make the space disappear as well.
if ( x == y) {
myElement.style.visibility = 'visible';
} else {
myElement.style.visibility = 'hidden';
}
26. How to change style on an element?
Between CSS and JavaScript is a weird symmetry. CSS style rules are laid on top of the DOM. The CSS property names like "font-weight" are transliterated into "myElement.style.fontWeight". The class of an element can be swapped out. For example:
document.getElementById("myText").style.color = "green";
document.getElementById("myText").style.fontSize = "20";
-or-
document.getElementById("myText").className = "regular";
27. How to remove the event listener?
<script type="text/javascript">
document.getElementById("hitme4").removeEventListener("click", hitme4, false);
</script>
Key Events
"onkeydown", "onkeypress", "onkeyup" events are supported both in ie and standards-based browsers.
<script type="text/javascript">
function setStatus(name,evt) {
evt = (evt) ? evt : ((event) ? event : null); /* ie or standard? */
var charCode = evt.charCode;
var status = document.getElementById("keyteststatus");
var text = name +": "+evt.keyCode;
status.innerHTML = text;
status.textContent = text;
}
</script>
<form action="">
<input type="text" name="keytest" size="1" value=""
onkeyup="setStatus('keyup',event)"
onkeydown="setStatus('keydown',event)"
/>
<p id="keyteststatus">status</p>
</form>
28. How to Handle Event Handlers?
You can add an event handler in the HTML definition of the element like this,
<script type="text/javascript"><!--
function hitme() {
alert("I've been hit!");
}
// -->
</script>
<input type="button" id="hitme" name="hitme" value="hit me" onclick="hitme()"
Or, interestingly enough you can just assign the event's name on the object directly with a reference to the method you want to assign.
<input type="button" id="hitme2" name="hitme2" value="hit me2"/>
<script type="text/javascript"><!--
function hitme2() {
alert("I've been hit too!");
}
document.getElementById("hitme2").onclick = hitme2;
// -->
</script>
You can also use an anonymous method like this:
document.getElementById("hitme3").onclick = function () { alert("howdy!"); }
You can also use the the W3C addEvventListener() method, but it does not work in IE yet:
<input type="button" id="hitme4" name="hitme4" value="hit me4"/>
<script type="text/javascript"><!--
function hitme4() {
alert("I've been hit four!");
}
29. How to getting values from cookies to set widgets?
function getCookieData(labelName) {
//from Danny Goodman
var labelLen = labelName.length;
// read cookie property only once for speed
var cookieData = document.cookie;
var cLen = cookieData.length;
var i = 0;
var cEnd;
while (i < cLen) {
var j = i + labelLen;
if (cookieData.substring(i,j) == labelName) {
cEnd = cookieData.indexOf(";",j);
if (cEnd == -1) {
cEnd = cookieData.length;
}
return unescape(cookieData.substring(j+1, cEnd));
}
i++;
}
return "";
}
//init() is called from the body tag onload function.
function init() {
setValueFromCookie("brand");
setValueFromCookie("market");
setValueFromCookie("measure");
}
function setValueFromCookie(widget) {
if( getCookieData(widget) != "") {
document.getElementById(widget).value = getCookieData(widget);
}
}
//if you name your cookies the widget ID, you can use the following helper function
function setCookie(widget) {
document.cookie = widget + "=" +
escape(document.getElementById(widget).value) + getExpirationString();
}
30. How to setting a cookie with the contents of a textbox?
Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy "escape()" function to encode the values, and "unescape()" to retrieve them.
//Sets cookie of current value for myTextBox
function TextBoxOnchange() {
var myBox = window.document.getElementById(myTextBox");
document.cookie = "myTextBox="+ escape(myBox.value) + getExpirationString();
}
//return a string like ";expires=Thu, 5 Jan 2006 16:07:52 UTC"
function getExpirationString() {
var exp = new Date();
var threemonths = exp.getTime()+(120*24*60*60*1000);
exp.setTime(threemonths);
return ";expires="+exp.toGMTString();
}
This is called from the event handler in the HTML.
<input name="myTextBox" type="text" id="myTextBox"
onchange="javascript:TextBoxOnchange()" />
31. How to open a window with no toolbar, but with the location object?
window.open
(
"http://www.globalguideline.com",
"Online Web Tutorials",
"resizable=yes, " +
"status=yes," +
"toolbar=yes," +
"location=yes," +
"menubar=yes," +
"scrollbars=yes," +
"width=800," +
"height=400"
);
32. How to create an input box?
Below line will help us how to create a Input box in JavaScript....
prompt("What is your name?");
33. How to create a confirmation box?
Below line will help us how to create a Confirmation box in JavaScript....
confirm("Do you really want to launch the missile today. HuM?");
34. How to create a popup warning box?
Below line will help us how to create a popup warning box in JavaScript....
alert('Warning: Please enter an integer between 0 and 100.');
35. Explain unescape() and escape() in JavaScript?
These are similar to the decodeURI() and encodeURI(), but escape() is used for only portions of a URI.
<script type="text/javascript">
var myvalue = "Sir Robbert Scott";
document.write("Original myvalue: "+myvalue);
document.write("<br />escaped: "+escape(myvalue));
document.write("<br />uri part: "&author="+escape(myvalue)+""");
</script>
If you use escape() for the whole URI... well bad things happen.
<script type="text/javascript">
var uri = "http://www.google.com/search?q=Online Web Tutorials"
document.write("Original uri: "+uri);
document.write("
escaped: "+escape(uri));
</script>