Differences between window.onload/onunload and body.onload/onunload - javascript

I have read the answers for the question window.onload vs <body onload=""/>. In that Q&A, many claim that window.onload and body.onload are identical. This is not what I experience.
Consider the two test pages:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>test 1</title>
<script type="text/javascript">
var initialSelectedIndex = 0;
function resetMenu()
{
document.getElementById("fruitMenu").selectedIndex = initialSelectedIndex;
}
</script>
</head>
<body onload="resetMenu();" onunload="resetMenu();">
<br />
<select id="fruitMenu">
<option value ="apple">apple</option>
<option value ="banana">banana</option>
<option value ="strawberry">strawberry</option>
<option value ="grape">grape</option>
</select>
<p>google
</p>
</body>
</html>
And:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>test 2</title>
<script type="text/javascript">
var initialSelectedIndex = 0;
function resetMenu()
{
document.getElementById("fruitMenu").selectedIndex = initialSelectedIndex;
}
window.onload = resetMenu();
window.onunload = resetMenu();
</script>
</head>
<body>
<br />
<select id="fruitMenu">
<option value ="apple">apple</option>
<option value ="banana">banana</option>
<option value ="strawberry">strawberry</option>
<option value ="grape">grape</option>
</select>
<p>google
</p>
</body>
</html>
With the "test 1" page, if you select an item from the drop down menu and the click the link to navigate away from the page and then hit the back button the menu will be reset to its initial state. This doesn't happen for the "test 2" page though. Why?
While this is a test, my goal is to do something similar on an aspx page using RegisterStartupScript or RegisterClientScriptBlock so I want to be able to recreate the behaviour of "test 1" without using the body onload/onunload but using window.onload/onunload.

Crescent is correct, by using:
window.onload = resetMenu();
You are making window.onload equal to the return value of the resetMenu function, rather than providing the function which should be called onload (and unload). So you should use:
window.onload = resetMenu;
window.onunload = resetMenu;
But why do you need to reset the menu when the page is unloaded?
Note: You can also use anonymous functions as the onload handler :)

Related

How to display INPUT TYPE on Selection?

I know its a simple but i tried many solutions but i failed. I have a form on which I use <select> tag in <option> i use two values coo and uh i want that when user select uh then it display an extra input type field.
Here is my code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​
<script>
$('#s_designation').on('change',function(){
if ($(this).val() === "uh") {
$("#uh").show()
}
else {
$("#uh").hide()
}
});
</script>
<title>Untitled Document</title>
</head>
<body>
<label for="db">Choose type</label>
<select name="s_designation" id="s_designation">
<option value="coo">Chief Operating Officer</option>
<option value="uh">Unit Head</option>
</select>
<div id="uh" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Designation"/>
</div>
</body>
</html>
I just tested your code and it works fine:
Link:https://jsfiddle.net/g95pyqw6/
Edit: But that could be because of JSfiddle.
Try to uncomment the first line of Javascript, that should help! :-)
I hope I could help you out. If you need more help, feel free to write a comment :-)
You jQuery code is executing before the document loads, which means the select element is not visible to jQuery, and jQuery won't throws error if it didn't find any given element.
use the $(document).ready like the following, it will load your code after document loads:
<head>
-------
-------
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
$(document).ready(function() {
$('#s_designation').on('change',function(){
if( $(this).val()==="uh") {
$("#uh").show()
}
else {
$("#uh").hide()
}
});
});
</script>
-------
</head>
if you want to execute jQuery code after page loading
you simply place your jQuery code before </body> tag like the following:
<body>
-------
-------
<script>
$('#s_designation').on('change',function(){
if( $(this).val()==="uh") {
$("#uh").show()
}
else {
$("#uh").hide()
}
});
</script>
</body>
here your Working code (checked on my local machine) answer is here for your problem Jquery not working from Google CND
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​
<script>
$(function() {
$('#s_designation').on('change',function(){
if( $(this).val()=="uh"){
$("#uh").show()
}
else{
$("#uh").hide()
}
});});
</script>
<title>Untitled Document</title>
</head>
<body>
<label for="db">Choose type</label>
<select name="s_designation" id="s_designation">
<option value="coo">Chief Operating Officer</option>
<option value="uh">Unit Head</option>
</select>
<div id="uh" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Designation"/>
</div>
</body>
</html>
In your code you have commented the $(function() line :
You are also missing the required jquery library files
Please add this to your html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Fiddle: http://jsfiddle.net/0mqze5ny/
$(function () {
$('#s_designation').on('change', function () {
if ($(this).val() === "uh") {
$("#uh").show()
} else {
$("#uh").hide()
}
});
})

Please Help in finding out the Correct Javascript code for me... Please

Here I have two HTML pages, First_page.html and Second_page.html,
In First_page.html I have a code that redirects to a page when a link is clicked with a certain URL parameter.
First_page.html's Code is like this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
one<br />
two<br />
three<br />
four
</body>
</html>
And in the Second_page.html I have a code that reads the URL parameter and change the Dropdowns Menu according to it.
Second_Page.html's Code is like This
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function show(choice) {
var success = -1;
for (var i=0; i < document.form1.selecoption.length; i++) {
if (document.form1.selecoption.options[i].value == choice)
success = [i];
}
document.form1.selecoption.selectedIndex=success;
}
</script>
</head>
<body onLoad="var choice = location.href.split('?')[1].split('=')[1];show(choice);">
<form name="form1">
<select name="selecoption">
<option value="1">ONE</option>
<option value="2">TWO</option>
<option value="3">THREE</option>
<option value="4">FOUR</option>
</select>
</form>
</body>
Now, what I want is that how do i select two different dropdown menu's i.e "selecoption" & "selecsecondoption" in Second_page.html using URL Parameter. Please help....
First, you have to use the correct URL format. Passing value(s) to URL needs corresponding variable name(s). So the corrected First_page.html file should be like below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
one<br />
two<br />
three<br />
four
</body>
</html>
And here's the fixed Second_Page.html file. All script code are moved into the script code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function getUrlVar(varName) { //returns empty string if variable name not found in URL
if (!varName) return ''; //no variable name specified. exit and return empty string
varName = varName.toLowerCase(); //convert to lowercase
var params = location.search; //get URL
if (params == '') return ''; //no variables at all. exit and return empty string
var vars = params.split('?')[1].split('&'); //get list of variable+value strings
for (var i = 0; i < vars.length; i++) { //check each variable
var varPair = vars[i].split('='); //split variable and its value
if (varPair.length > 1) { //has "=" separator
if (varPair[0].toLowerCase() == varName) { //same variable name?
return varPair[1]; //found variable. exit and return its value
} //else: check next variable, if any
} //else: is not an array. i.e.: invalid URL variable+value format. ignore it
}
return ''; //no matching variable found. exit and return empty string
}
function show() {
var value = getUrlVar('selecoption'); //get variable value
if (!value) return; //variable not found
if (parseInt(value) == NaN) return; //value is not a number
var sel = document.getElementById('form1').selecoption;
for (var i=0; i < sel.length; i++) {
if (sel.options[i].value == value) {
document.getElementById('form1').selecoption.value = value;
return;
}
}
}
</script>
</head>
<body onLoad="show();">
<form id="form1">
<select name="selecoption">
<option value="1">ONE</option>
<option value="2">TWO</option>
<option value="3">THREE</option>
<option value="4">FOUR</option>
</select>
</form>
</body>
</html>
Try this :
<script type="text/javascript">
document.getElementById('selecoption').value=String(choice);
</script>
at the end of the Second_Page.html

Display a text box when an option is selected

I used a radio button to display the dropdown list with three options. I need to display a textbox when the user selects the blank option. If anyone has a suggestion that would steer me in the right direction, I would be grateful.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>test</title>
<style type="text/css" media="screen">
.hide{
display:none;
}
</style>
</head>
<body>
<form name="frm1" method="POST" action="">
<p>Select type of exception:<br />
<div id="tabs">
<div id="nav">
Waiver:<input type="radio" name="tab" value="pickfrom" class="div5" />
</div>
<div id="div5" class="tab"><br />
<label>Reason for Waiver</label>
<select name="selWaiver" id="waivers" onchange="if(this.selected index==blank){this.form['box'].style.visibility='visible'}else{this.form['box'].style.visibility='hidden'};">
<option value="reason">Reason</option>
<option value="newReason">New Reason</option>
<option value="blank">Blank</option>
</select>
</div>
</div>
<script type="text/javascript" charset="utf-8">
(function(){
var tabs =document.getElementById('tabs');
var nav = tabs.getElementsByTagName('input');
/*
* Hide all tabs
*/
function hideTabs(){
var tab = tabs.getElementsByTagName('div');
for(var i=0;i<=nav.length;i++){
if(tab[i].className == 'tab'){
tab[i].className = tab[i].className + ' hide';
} }
}
/*
* Show the clicked tab
*/
function showTab(tab){
document.getElementById(tab).className = 'tab'
}
hideTabs(); /* hide tabs on load */
/*
* Add click events
*/
for(var i=0;i<nav.length;i++){
nav[i].onclick = function(){
hideTabs();
showTab(this.className);
}
}
})();
</script>
</form>
</body>
</html>
<select name="selWaiver" id="waivers" onchange='if ($(this).val()=="") {
$("#box").show(); }else{
$("#box").hide();}'>
I recommend JQuery because it will save you a lot of cross browser compatibility issues!
Are you using jQuery in this project. It is so much easier to perform DOM manipulation using the jQuery library. I would use the jQuery toggle() method for this (more info at http://api.jquery.com/css). You could do something like this on the click event for the blank option:
$('.hide').toggle();
Javascript version (untested) :
<select name="selWaiver" id="waivers" onchange='check(this);'>
<script>
function check(sel)
{
var value=frm1.selWaiver.options[frm1.selWaiver.options.selectedIndex].value;
//alert(value) to see if it works
var box=document.getElementById("box");
if (value=="")
box.style.display="block";
else
box.style.display="none";
}
</script>

Javascript Problems in Firefox but not in IE Debugging problems VIsual Studio 2010

Help I'm very new with web developing using ASP.NET. Why is the my web app does not give the desired output like IE does when debugging my code below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
h1{color:Blue}
h2{color:Red}
</style>
<script type="text/javascript">
function ShowColor() {
alert("You selected " + SelectColor.value);
BodyContent.style.backgroundColor = SelectColor.value;
}
</script>
</head>
<body>
<div id="BodyContent">
<h1>HelloWorld</h1>
<h2>Welcome</h2>
<p>
This is my first Web Page</p>
<hr />
Please select color:
<select id="SelectColor">
<option value="white">white</option>
<option value="yellow">yellow</option>
<option value="silver">silver</option>
</select>
<input id="ButtonColor" type="button" value="Select" onclick="ShowColor()" />
</div>
</body>
</html>
Problem is that FF does not executes the javascript "ShowColor" when i clicked the Select button but IE does.
function ShowColor() {
alert("You selected " + SelectColor.value);
BodyContent.style.backgroundColor = SelectColor.value;
}
Your javascript function should be as follows:
function ShowColor() {
alert("You selected " + document.getElementById("SelectColor").value);
document.body.style.backgroundColor = document.getElementById("SelectColor").value;
}
You need to select the actual elements by using javascript. For example document.gelElementById("id of element"), and then change the documents color. This should work in any browser.
The function now shows the appropriate selected value and actually changes the background of the webpage. Mark as answer if this helped you out.
try this:
<script type="text/javascript">
var selected;
function alertselected(selectobj) {
selected = selectobj.selectedIndex;
}
function ShowColor() {
alert("You selected " + selected);
elm = document.getElementById("sample");
document.getElementById("BodyContent").style.backgroundColor = elm.options[elm.selectedIndex].value;
}
html:
<div id="BodyContent"><select id="sample" onChange="alertselected(this)">option>white</option><option>yellow</option><option>silver</option>
<input id="ButtonColor" type="button" value="Select" onclick="ShowColor()" /></div>

HTML + Passing Param b/w Parent & Child

It might be a simple, but the funny thing is i've tried it for almost 2-3hrs and haven't been able to solve it :(.
I have a parent window, which has a text box, and it has a value. I do a window.open and open a client and try to read the value of the parent, but unable to get the value.
Any help!!
I've tried
window.parent.document.getElementById(window.name)
window.parent.document.getElementById('test').value
window.opener.document.getElementById('teast').value
window.parent.opener.document.getElementById('teast').value
window.opener.parent.document.getElementById('teast').value
Almost all the permutation and combination. And its pure HTML.
Due to security restrictions, Javascript is unable to access documents that reside on a separate domain from the current one. So, if your parent is on a different domain from the child, this will never work.
window.opener.document.getElementById('test').value should work.
I've tried that, it ain't work. I'm posting the code
test.html
<html>
<head>
<title>Chat</title>
</head>
<body>
<div id="chatMessages"></div>
<script>
var newWin = null;
var OpenWindow = null;
function popUp(strURL, strType, strHeight, strWidth) {
if (newWin != null && !newWin.closed)
newWin.close();
var strOptions="";
if (strType=="console")
strOptions="resizable,height="+
strHeight+",width="+strWidth;
if (strType=="fixed")
strOptions="status,height="+
strHeight+",width="+strWidth;
if (strType=="elastic")
strOptions="toolbar,menubar,scrollbars,"+
"resizable,location,height="+
strHeight+",width="+strWidth;
alert(window.parent.document.getElementById(window.name));
newWin = window.open(strURL, 'alertWindow', strOptions);
//newWin.document.getElementById("child").value='Str';
newWin.focus();
// send_data(data);
}
function chat() {
popUp('../alert.jsp','console',250,600);
}
</script>
<form name="AlertReceiverOnHeader" onclick="chat()">
<input type="text" value="teast" id="teast" name="teast"/>
</form>
</html>
child.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Alert</title>
</head>
<body onload="load()">
<script language="JavaScript">
function load() {
alert('In load');
alert("001="+window.parent.document.getElementById('teast'));
alert("002="+window.parent.document.getElementById(window.name));
alert("003="+window.opener.document.getElementById('teast').value);
}
</script>
<form name="child">
<input type="text" id="child" value="child"/>
</form>
</body>
</html>

Categories