Populate HTML listbox using javascript function on page load - javascript

I have a HTML Listbox and I need to add values to it on the page load. I have tried to call a JS function on page load event on both <body> tag and <select> tag but it does not execute the the function.
<body onload='popListbox(<%=session.getAttribute("objNames")%>)'>
<select id="lstObjects" onload='popListbox(<%=session.getAttribute("objNames")%>)'>
If I try onclick it executes fine but not in onload event. Can someone help me with this.?
UPDATE: my JS function
function popListbox(objList){
var select = document.getElementById("lstObjects");
var objects = objList;
var objects_array = [];
for(var i in objects) {
if(objects.hasOwnProperty(i) && !isNaN(+i)) {
objects_array[+i] = objects[i];
}
}
for(var i = 0; i < objects_array.length; i++) {
var opt = objects_array[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}

try document.ready
$( document ).ready(function() {
//your code here
});

What's the JS function?
I suspect, because only the body tag has an onload handler, perhaps your js function is not aware of the element context when it is triggered from document root.
function popListbox(objList){
var select = document.getElementById('lstObjects');
for(i=0,ic=objList.length;i<ic;++i) {
var el=document.createElement('option');
el.textContent=objList[i];
el.value=objList[i];
select.appendChild(el);
}
}
I don't know why it doesn't work but I rewrote it because it's the same result

Related

Replace All Words In Document Body Doesn't Work

Firstly sorry for my english, i have code that doesnt work when I execute it on
<script language="javascript" src="/thecode.js"></script>
I put thecode.js on footer
var msg=document.body.innerHTML;
for(var i=0;i<msg.length;i++){
var tx=document.body[i].innerHTML;
tx=tx.replace(/dog/ig,'animal');
tx=tx.replace(/apple/ig,'fruit');
tx=tx.replace(/\[VIdEo\]/ig,'Video');
tx=tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
document.body.innerHTML=tx;}
I think i dont make any fault, but when i execute it, its doesnt work.
thank for your attention... :)
no need to iterate body element
try this:
want to change to with that js? i have used to make it
function addTitleToSurveyUrls() {
var elements = document.getElementsByTagName('a');
for(var el in elements) {
var element = elements[el];
var href = element.getAttribute("href");
if(href.indexOf('survey_')>-1) {
element.setAttribute('title', 'Some TITLE HERE');
}
}
}
function replaceBodyElements() {
var tx=document.body.innerHTML;
tx = tx.replace(/dog/ig,'animal');
tx = tx.replace(/apple/ig,'fruit');
tx = tx.replace(/\[VIdEo\]/ig,'Video');
tx = tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
document.body.innerHTML=tx;
}
window.onload = function(){
replaceBodyElements();
addTitleToSurveyUrls();
// ... some another operations
};
also
document.onreadystatechange = function () {
var state = document.readyState;
if(state == 'complete') {
replaceBodyElements();
addTitleToSurveyUrls();
}
}​
I've used onload event because maybe document has dynamic elements and etc. so better wait while all elements get loaded and change it.
or You can replace window.onload with window.document.onload

Issue adding event with addEventListener to Input in documentFragment

I am creating a div using createDocumentFragment(). In the Div is a table with a list of input. When you click on any of the checkboxes I want to trigger the alert('Yes'). when I add the event it does not add it to the input but with Firefox it seems to call the alert when it is added to the table.
Can someone explain what I am doing wrong?
function deptFilter(rPattern)
{
var lclData = JSON.parse(rPattern);
var loc = document.getElementById('show2');
var arrayKeys = Object.keys(lclData);
var outputData;
var LCL_List
var LCLTables;
var LCLtd;
var LCLtr;
var LCLInput;
var LCLDiv;
var LCL_List = document.createDocumentFragment(document.createElement('DIV'));
LCL_List.id = 'LCLTable';
for(var x = 0; x < arrayKeys.length; x++)
{
LCLDiv = LCL_List.appendChild(document.createElement('DIV'));
LCLTables = LCLDiv.appendChild(document.createElement('TABLE'));
for(var y = 0; y < lclData[arrayKeys[x]].length; y++)
{
LCLtr = LCLTables.appendChild(document.createElement('TR'));
LCLtd = LCLtr.appendChild(document.createElement('TD'));
LCLInput = LCLtd.appendChild(document.createElement('INPUT'));
LCLInput.id = lclData[arrayKeys[x]][y]['Name'];
LCLInput.type='checkbox';
LCLInput.addEventListener("click", alert("Yes"));
}
}
loc.appendChild(LCL_List);
}
When you install an event handler like this:
LCLInput.addEventListener("click", alert("Yes"));
You're executing alert() immediately and then passing the return value from that to addEventListener(). This is obviously NOT what you want. Instead, you need to pass a function reference to addEventListener and that function will then call your alert() sometime later:
LCLInput.addEventListener("click", function(e) {
alert("Yes");
});
Or you can define a named function and pass just its name:
function handleClick(e) {
alert("Yes");
}
LCLInput.addEventListener("click", handleClick);
This is the way to add event listner:
LCLInput.addEventListener("click", function() {
alert("Yes");
});

How to collect all script tags of HTML page in a variable

I would like to collect all the <script> ....</script> code section present in the HTML page in some variable.
What should be the simpler way to do this, Any idea how it can be retrieved using JavaScript.??
Any help will be greatly appreciated.
To get a list of scripts you can use
document.getElementsByTagName("script"); by tag
document.scripts; Built-in collection
document.querySelectorAll("script"); by selector
$("script") jQuery by selector
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src) console.log(i, scripts[i].src)
else console.log(i, scripts[i].innerHTML)
}
// To get the content of the external script
// - I use jQuery here - only works if CORS is allowing it
// find the first script from google
var url = $("script[src*='googleapis']")[0].src;
$.get(url,function(data) { // get the source
console.log(data.split("|")[0]); // show version info
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
console.log("Inline script");
</script>
<script>
function bla() {
console.log("Other inline script");
}
</script>
The simplest way is probably document.scripts
You would do:
var scripts = document.getElementsByTagName( 'script' );
Now scripts is a NodeList (like an array), and you can access each one using scripts[0], scripts[1] and so on.
try this
var scripts = document.getElementsByTagName("script");
Without jQuery :
var scripts = document.getElementsByTagName("script");
With jQuery :
var scripts = $("script");
Here you go --
(function () {
'use strict';
let logscript = function () {
let js = document.scripts;
for (let i = 0; i < js.length; i++) {
if (js[i].src) {
console.log(i, js[i].src);
} else {
console.log(i, js[i].innerHTML);
}
}
};
if (document.readyState === 'complete') {
logscript();
} else {
window.addEventListener('load', logscript);
}
})();

Internet Explorer throwing error on getElementById

I'm having trouble with some javascript which uses getElementById. It works fine in FF, Safari and Chrome, but IE(8 - haven't tried others) bails out.
The relevant bit of html is a div called topnav:
<div id="topnav">
... some HTML ...
<div>
<div id="sub_1" class="lowernav">
... some HTML ...
</div>
<div id="sub_2" class="lowernav">
... some HTML ...
</div>
In my javascript, I want to find topnav. The full code (up to where it bails) is this:
<script>
window.onload = init();
function init() {
// Show current menu
showCurrentMenu();
}
function showCurrentMenu() {
hideMenus(); // Hide all menus and then show the current one
topnav = document.getElementById('topnav');
... rest of code ...
}
function hideMenus() {
var divlist = document.getElementsByTagName('div');
for(var ii=0; ii<divlist.length; ii++) {
if(divlist[ii].className != divlist[ii].className.replace('lowernav','')) {
divlist[ii].className += ' hidden';
}
}
}
... then some other code it hasn't reached yet...
Am I doing something wrong here? It may well be something really obvious, but for the life of me, I can't see it! All advice is much appreciated.
ETA: Ok, here's the whole code, as it currently stands:
<script>
window.onload = init;
function init() {
// Show current menu
showCurrentMenu;
// Attach 'onmouseover' event to main menu items
topnav = document.getElementById('topnav');
// Get all items in list
var menulist = topnav.getElementsByTagName('a');
for(var ii=0; ii<menulist.length; ii++) {
menulist[ii].onmouseover = showMenu;
}
document.getElementById('mainHomeNav').onmouseout = restoreMenu;
}
function restoreMenu(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
if (targ.id == "mainHomeNav") {
showCurrentMenu;
}
}
function hideMenus() {
var divlist = document.getElementsByTagName('div');
for(var ii=0; ii<divlist.length; ii++) {
if(divlist[ii].className != divlist[ii].className.replace('lowernav','')) {
divlist[ii].className += ' hidden';
}
}
}
function showCurrentMenu() {
hideMenus;
topnav = document.getElementById('topnav');
// Get all items in list
var menulist = topnav.getElementsByTagName('a');
for(var ii=0; ii<menulist.length; ii++) {
if(menulist[ii].className != menulist[ii].className.replace('thisSection','')) {
var thisid = menulist[ii].id;
var thissubmenu = document.getElementById(thisid + '_sub');
thissubmenu.className = thissubmenu.className.replace(/hidden/g,'');
}
}
}
function showMenu() {
hideMenus;
// show this menu
var submenu_id = this.id + '_sub';
var submenu = document.getElementById(submenu_id);
submenu.className = submenu.className.replace(/hidden/g,'');
}
</script>
The problem is
window.onload = init();
This will call the init function immediately, and then use its return value as the page's onload function. You need:
window.onload = init;
which will call the init function only after the page has fully loaded.
I found the problem - I didn't have 'var' in front of 'topmenu'.
So instead of
topnav = document.getElementById('topnav');
it should have been
var topnav = document.getElementById('topnav');
Thanks everyone for the help.
Your problem lies in the following line:
window.onload = init(); // this will CALL init() and assign the return value
Since init doesn't return anything, window.onload will be undefined.
Now the reason for it not working in IE, but in other Browsers is that those other Browsers might already have parsed a part of the DOM and therefore the call to showCurrentMenu works.
But that could just as well break, since from a technical point of view the document is not guaranteed to be loaded, to fix that you have to assign the actual function reference to window.onload by doing:
window.onload = init;

Appending target="_blank" to links in an iframe without using <body onload>

I'm trying to change the links in an iframe to load in a new window instead of the iframe itself. Currently I use this code in head:
$(document).ready(function() {
var oIFrame = document.getElementById("iframeID");
var oDoc = (oIFrame.contentWindow || oIFrame.contentDocument);
if(oDoc.document) oDoc = oDoc.document;
var links = oDoc.getElementsByTagName("a");
for(var i=0; i<links.length; i++) { links[i].target="_blank"; }
});
However, the code above is triggered before the iframe is fully loaded with its contents. I know this code would work if it's triggered in the body onload attribute, but I'd like to avoid that method and implement it in a function or a file instead.
Try
$("#iframeid").load(function(){
// your code
});
Have a go with:
$(document).ready(function() {
var oIFrame = document.getElementById("iframeID");
var oDoc = (oIFrame.contentWindow || oIFrame.contentDocument);
if(oDoc.document) oDoc = oDoc.document;
$(oDoc).ready(function(){
var links = oDoc.getElementsByTagName("a");
for(var i=0; i<links.length; i++) { links[i].target="_blank"; }
}
});
You could set a timeout function periodically checking if
iframe.document.readyState == 'complete'

Categories