I followed a tutorial on Youtube about localStorage and everything went fine. After that I tried to mess around with the concepts and wanted to add a button to remove the localStorage (id ="btnClear").
Now I've tried everything but it doesnt let me remove the storage. I think its because I declared the constants inside the function and I might have to store them somewhere outside and stringify the input. But can I clear the localStorage somehow even in this scenario?
<body>
<content>
<fieldset>
<legend>Insert Data</legend>
<input type="text" id="inpKey" placeholder="Insert Key.." />
<input type="text" id="inpValue" placeholder="Insert Value.." />
<button type="button" id="btnInsert">Insert</button>
</fieldset>
<fieldset>
<legend>Local Storage</legend>
<div id="lsOutput"></div>
<br />
<button type="button" id="btnClear">Clear</button>
</fieldset>
</content>
</body>
<script type="text/javascript">
const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const lsOutput = document.getElementById("lsOutput");
const btnClear = document.getElementById("btnClear");
btnInsert.onclick = function () {
const key = inpKey.value;
const value = inpValue.value;
if (key && value) {
localStorage.setItem(key, value);
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
lsOutput.innerHTML += `${key}: ${value}`;
}
//BUTTON CLEAR
btnClear.onclick = function () {
localStorage.clear();
};
</script>
Check your local storage in the browser. Your code actually does clear the localStorage. What you are missing is to update your UI. Replace your Button clear code with that:
btnClear.onclick = function () {
localStorage.clear();
if(localStorage.length === 0)
lsOutput.innerHTML = "";
};
Here is a tutorial how you check your local storage in chrome for example: How to view or edit localStorage
Have a look here, I have update all you code from HTML to JS.
You can test it on jsfiddle as stackoverflow will throw this error:
{
"message": "Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.",
"filename": "https://stacksnippets.net/js",
"lineno": 37,
"colno": 33
}
Also, It is better to use document.addEventListener with most of your events (as they provide you with reacher experience)
See more on events here
A quote from this URL:
The significant drawback with inline events is that unlike event
listeners described above, you may only have one inline event
assigned. Inline events are stored as an attribute/property of the
element[doc],
meaning that it can be overwritten.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to clear localStorage on button click</title>
</head>
<body>
<content>
<fieldset>
<legend>Insert Data</legend>
<input type="text" id="inpKey" placeholder="Insert Key.." />
<input type="text" id="inpValue" placeholder="Insert Value.." />
<button type="button" id="btnInsert">Insert</button>
</fieldset>
<fieldset>
<legend>Local Storage</legend>
<ul id="outputList"></ul>
<br />
<button type="button" id="btnClear">Clear</button>
</fieldset>
</content>
<script type="text/javascript">
const printLSContent = function (el) {
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
let value = localStorage.getItem(key);
let li = document.createElement('li');
li.innerHTML = `K: ${key}; V: ${value}`;
el.appendChild(li);
}
}
document.addEventListener("DOMContentLoaded", function (event) {
const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const outputList = document.getElementById("outputList");
const btnClear = document.getElementById("btnClear");
// element.addEventListener(event, handler[, options]); // type - event type; listener - event handler; options -
btnInsert.addEventListener('click', function () {
const key = inpKey.value;
const value = inpValue.value;
localStorage.setItem(key, value);
location.reload();
}, false);
printLSContent(outputList);
// //BUTTON CLEAR
btnClear.addEventListener('click', function () {
localStorage.clear();
location.reload();
}, false);
});
</script>
</body>
</html>
Related
I want to save the value of a week Input in a Variable.
Additionally, I want to output it in a span.
I tried this:
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
var kw = document.getElementById("week-selector").value;
document.getElementById("kalenderwoche").innerHTML = kw;
Your code works. You just need an event handler
Here I made one that can be reused on load in case the selector has a value already
window.addEventListener("DOMContentLoaded", () => { // when page has loaded
const kw = document.getElementById("kalenderwoche");
const ws = document.getElementById("week-selector");
let kwValue; // you wanted to save it for later?
const setValue = () => kwValue = kw.textContent = ws.value || "";
ws.addEventListener("input", setValue)
setValue(); // initialise
console.log(kwValue); // saved value
});
<input type="week" name="week" id="week-selector" value="2022-W50" />
<span id="kalenderwoche"></span>
you have to add eventListener to week input
var kw = document.getElementById("week-selector")
kw.addEventListener('change', (e) => {
console.log("e=>>>>", e.target)
document.getElementById("kalenderwoche").innerHTML = e.target.value;
})
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
<!DOCTYPE html>
<html>
<body>
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
<script>
document.getElementById("week-selector").addEventListener('change', function() {
document.getElementById("kalenderwoche").innerHTML = this.value
})
</script>
</body>
</html>
I currently use the following code to save input after browser refresh.
<style>textarea, input {
width:100%;
height:50px
}
</style>
<textarea class='' id='thetext' onkeyup='saveValue(this)'/><br/><br/>
<button id='' onclick='shift()'>Shift</button><br/><br/>
<script>
var input = document.getElementById("thetext");
function shift() { input.value = input.value.toUpperCase()}
</script>
<script>document.getElementById("thetext").value = getSavedValue("thetext");
function saveValue(e){
var id = e.id;
var val = e.value;
localStorage.setItem(id, val);
}
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}</script>
When a user enters something in the textarea, and leaves the window, the textarea gets stored in local storage, thanks to the onkeyup event listener.
However, if the user presses the shift button and leaves the browser, the uppercase text value doesn't get stored in textarea because there's no onkeyup action after button press.
I tried various event listeners instead of onkeyup, like onblur, onunload but none of them are working. Is there any event listener which can record the actions then and there? Or any way else?
PS - This code isn't working on Stackoverflow, don't know why, however it's working on my webpage. So, Please ignore this issue.
You can just call the saveValue() method after you´ve done all your stuff you need with the input.
just update the saved value by calling the savevalue() method you defined like this input.value = input.value.replace(); input.saveValue()
Run this in your own environment.
<form>
<input name="first" placeholder="first" />
<input name="last" placeholder="last" />
</form>
<script>
const form = document.querySelector('form');
const FORM_DATA = 'FORM-DATA';
window.addEventListener('DOMContentLoaded', () => {
const fromStorage = localStorage.getItem(FORM_DATA);
if (!fromStorage) return;
const json = JSON.parse(fromStorage);
for (const input of form.querySelectorAll('input')) {
input.value = json[input.name];
}
});
form.addEventListener('keyup', () => {
const formData = Object.fromEntries([...new FormData(form)]);
localStorage.setItem(FORM_DATA, JSON.stringify(formData));
});
</script>
Here is an example that works :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Save input after refreshing</title>
</head>
<body>
<input id="myInput" type="text" />
<script>
function saveValue(inputElement) {
if (!inputElement) throw new Error('inputElement param is required');
const { id, value } = inputElement;
if (!id) throw new Error('inputElemend should have an id attribute');
localStorage.setItem(id, value);
}
function getSavedValue(inputElement) {
if (!inputElement) throw new Error('inputElement param is required');
const { id } = inputElement;
if (!id) throw new Error('inputElemend should have an id attribute');
const value = localStorage.getItem(id);
return value;
}
const input = document.querySelector('#myInput');
input.addEventListener("keyup", function(event) {
saveValue(event.target)
});
window.addEventListener('load', function() {
const value = getSavedValue(input);
input.value = value;
})
</script>
</body>
</html>
This code successfully takes the contents of the form and saves it to an ordered list, 2 more functions do the same thing but instead create a timestamp. I'm trying to take every li element that gets generated and save it to localStorage when you push the save button and then repopulate it again from the local storage when you push the "load" button. I can't get it to work come hell or high water. The load button does nothing, and oddly enough the "save" button acts as a clear all and actually removes everything rather then saving it. Console log shows no errors. I have the JavaScript below and the corresponding HTML.
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
document.getElementById("todoList").appendChild(newItem)
};
function save() {
const fieldvalue = querySelectorAll('li').value;
localStorage.setItem('item', JSON.stringify(item));
}
function load() {
const storedvalue = JSON.parse(localStorage.getItem(item));
if (storedvalue) {
document.querySelectorAll('li').value = storedvalue;
}
}
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="save()">Save</button>
<button id="load" onclick="load()">Load</button>
</form>
As #Phil and #Gary explained part of your problem is trying to use querySelectorAll('li') as if it would return a single value. You have to cycle through the array it returns.
Check the below code to give yourself a starting point. I had to rename some of your functions since they were causing me some errors.
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="saveAll()" type="button">Save</button>
<button id="load" onclick="loadAll()" type="button">Load</button>
</form>
<div id="todoList"></div>
<script>
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
//Had to add the element
document.getElementById("todoList").appendChild(newItem);
}
function saveAll() {
//Create an array to store the li values
var toStorage = [];
var values = document.querySelectorAll('li');
//Cycle through the li array
for (var i = 0; i < values.length; i++) {
toStorage.push(values[i].innerHTML);
}
console.log(toStorage);
//Can´t test this on stackoverflow se the jsFiddle link
localStorage.setItem('items', JSON.stringify(toStorage));
console.log(localStorage);
}
function loadAll() {
const storedvalue = JSON.parse(localStorage.getItem('items'));
console.log(storedvalue);
//Load your list here
}
</script>
Check https://jsfiddle.net/nbe18k2u/ to see it working
I have created a javascript script in which all clicks and action of a particular IP it tracked down when attached in a page. It all works fine except when the user searches something from an input field. I need to track that text which user has searched.
But I don't have any information regarding that input field i.e id or class also a page can have.
multiple input fields i.e A form for submission too.
I need to get that text when the enter key is pressed or any button(search) is pressed
In my case at present html page, I have below code.
<div class="navbar-form navbar-right">
<!-- Search Page -->
<div id="search-container" class="search-container" style="float: left;">
<div class="search-wrapper">
<div class="search-input-wrapper">
<input type="text" class="search-layouts-input" ng-model="searchQuery" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" placeholder="So, what are you looking for?" ng-keyup="$event.keyCode == 13 ? actionSearch() : null">
<button type="submit" class="s-layout-btn" ng-click="actionSearch();">
<svg id="Layer_1" width="20px" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="#222">
<defs>
<style>.cls-1{fill:none;stroke:#222;stroke-miterlimit:10;stroke-width:2px;}</style>
</svg>
</button>
</div>
</div>
</div>
<!-- Search Page -->
</div>
Is this the kind of thing that you're looking to implement? Of course most of it is pseudo code, but it's pretty straight-forward, just get all relevant inputs and buttons and whatnot, attach some event handler to them and update the application state.
I've included some basic functions that you may wish to fire in certain scenarios, such as onStateUpdate, there may be no need for this function, but it probably wouldn't hurt to keep it for the sake of simplcity.
I've used mostly ES6 oriented syntax because it allows you to achieve the same results with less code, I'm just that lazy.
The reason why I used a self invoked function just so there's no issues with variable names and nothing can be manipulated on the global scope, etc. If you'd like to read or know more about why self invoked functions can be pretty good, then I suggest you read sources such as this.
// Self invoked anonymous function.
(function() {
// The application state.
const state = {};
// Lazy way to use querySelectorAll
const $e = qs => document.querySelectorAll(qs);
// Make a copy of the state and make it global.
const getState = () => {
window.state = { ...state};
console.clear();
console.log(window.state);
};
// A function to run when the state updates.
const onStateUpdate = () => {
// Do some other stuff...
getState();
};
// Handle the key up event.
const inputHandler = (i, index) => i.onkeyup = () => {
i.id == null || i.id == '' ? i.setAttribute("id", index) : null;
const id = i.id;
state[id] = i.value;
onStateUpdate();
};
// Handle a button being clicked.
const clickHandler = btn => btn.onclick = onStateUpdate;
// Handle the enter key being pressed.
const enterHandler = e => e.keyCode == 13 ? onStateUpdate() : null;
// Assign all relevant events to the relevant functions.
const dispatchEvents = () => {
const inputs = $e("#search-container input[type=text]");
const buttons = $e("#search-container button");
inputs.forEach((i, index) => inputHandler(i, index));
buttons.forEach(b => clickHandler(b));
window.onkeypress = enterHandler;
};
// Fire the dispatch function.
dispatchEvents();
}());
<!-- this one does nothing as it's outside of the search-container element -->
<input type="text" id="testing" placeholder="I do nothing!" />
<div id="search-container">
<input type="text" id="test" />
<input type="text" id="demo" />
<input type="text" id="markup" />
<input type="text" />
<button>Search</button>
</div>
Older Syntax
// Self invoked anonymous function.
(function() {
// The application state.
var state = {};
// Lazy way to use querySelectorAll
var $e = function(qs) {
return document.querySelectorAll(qs);
};
// Make a copy of the state and make it global.
var getState = function() {
window.state = JSON.parse(JSON.stringify(state));
console.clear();
console.log(window.state);
};
// A function to run when the state updates.
var onStateUpdate = function() {
// Do some other stuff...
getState();
};
// Handle the key up event.
var inputHandler = function(i, index) {
i.onkeyup = function() {
if (i.id == null || i.id == '') {
i.setAttribute("id", index);
}
var id = i.id;
state[id] = i.value;
onStateUpdate();
};
};
// Handle a button being clicked.
var clickHandler = function(btn) {
btn.onclick = onStateUpdate;
};
// Handle the enter key being pressed.
var enterHandler = function(e) {
if (e.keyCode == 13) {
onStateUpdate();
};
};
// Assign all relevant events to the relevant functions.
var dispatchEvents = function() {
var inputs = $e("input[type=text]");
var buttons = $e("button");
inputs.forEach(function(i, index) {
inputHandler(i, index)
});
buttons.forEach(function(b) {
clickHandler(b)
});
window.onkeypress = enterHandler;
};
// Fire the dispatch function.
dispatchEvents();
}());
<input type="text" id="test" />
<input type="text" id="demo" />
<input type="text" id="markup" />
<input type="text" />
<button>Search</button>
i'm developing a meta search engine website, Soogle and i've used JS to populate select menu..
Now, after the page is loaded none of engines is loaded by default, user needs to select it on his own or [TAB] to it..
Is there a possibility to preselect one value from the menu via JS after the page loads?
This is the code:
Javascript:
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
function startSearch(){
var searchString=document.searchForm.searchText.value;
if(searchString.replace(/\s+/g,"").length > 0){
var searchEngine=document.searchForm.whichEngine.selectedIndex,
finalSearchString=arr[searchEngine][1]+searchString;
window.location=finalSearchString;
}
return false;
}
function checkKey(e){
var key = e.which ? e.which : event.keyCode;
if(key === 13){
return startSearch();
}
}
// SEARCH ENGINES INIT
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge","http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos","http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
HTML:
<body onload="addOptions();document.forms.searchForm.searchText.focus()">
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input name="searchText" type="text" onkeypress="checkKey(event);"/>
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select>
<br />
<input tabindex="2" type="button" onClick="return startSearch()" value="Search"/>
</form>
</div>
</body>
I appreciate that your question asks for a solution that utilises JavaScript, but having looked at the webpage in question I feel confident in making this point:
Your problem is that you are trying to use JavaScript for something that HTML itself was designed to solve:
<select name="whichEngine">
<option value="http://www.google.com/search?q=" selected="selected">Web</option>
<option value="http://images.google.com/images?q=">Images</option>
<option value="http://en.wikipedia.org/wiki/Special:Search?search=">Knowledge</option>
<option value="http://www.youtube.com/results?search_query=">Videos</option>
<option value="http://www.imdb.com/find?q=">Movies</option>
<option value="http://thepiratebay.org/search/">Torrents</option>
</select>
Fear not, though! You can still access all of the options from JavaScript in the same way that you did before.
function alertSelectedEngine() {
var e = document.getElementsByName("whichEngine")[0];
alert("The user has selected: "+e.options[e.selectedIndex].text+" ("+e.options[e.selectedIndex].value+")");
}
Please, forgive and listen to me.
I have modified the code to use jQuery. It is working fine in IE8, IE8 (Compatibility mode) and in FireFox.
<!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 id="Head1" runat="server">
<title>Index</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
// SEARCH ENGINES INIT
var arr = new Array();
arr[arr.length] = new Array("Web", "http://www.google.com/search?q=");
arr[arr.length] = new Array("Images", "http://images.google.com/images?q=");
arr[arr.length] = new Array("Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search=");
arr[arr.length] = new Array("Videos", "http://www.youtube.com/results?search_query=");
arr[arr.length] = new Array("Movies", "http://www.imdb.com/find?q=");
arr[arr.length] = new Array("Torrents", "http://thepiratebay.org/search/");
// SEARCH FORM INIT
function addOptions() {
// Add the options to the select dropdown.
var nOptions = arr.length;
var optionText = '';
for (var i = 0; i < nOptions; i++) {
optionText += '<option value="' + i + '">' + arr[i][0] + '</option>'
}
//alert('optionText = ' + optionText);
// Add the options to the select drop down.
$('select#whichEngine').html(optionText);
// set the second option as default. This can be changed, if required.
$('select#whichEngine option:eq(1)').attr('selected', true);
}
function startSearch() {
var searchEngineIndex = $('select#whichEngine option:selected').attr('value');
searchEngineIndex = parseInt(searchEngineIndex, 10);
var searchString = $('input#searchText').val();
if (searchEngineIndex >= 0 && searchString) {
var searchURL = arr[searchEngineIndex][1] + searchString;
//alert('location = ' + searchURL);
window.location.href = searchURL;
}
return false;
}
function checkKey(e) {
var character = (e.which) ? e.which : event.keyCode;
if (character == '13') {
return startSearch();
}
}
$(function() {
// Add the options to the select drop down.
addOptions();
// Add focus to the search text box.
$('input#searchText').focus();
// Hook the click event handler to the search button.
$('input[type=button]').click(startSearch);
$('input#searchText').keyup(checkKey);
});
</script>
</head>
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input id="searchText" name="searchText" type="text"/>
<span id="color"></span>
<select tabindex="1" id="whichEngine" name="whichEngine"></select>
<br />
<input tabindex="2" type="button"value="Search"/>
</form>
</div>
</body>
</html>
You had some errors in how you handle the <select> values and options. I would reorganize your JavaScript like this:
// SEARCH ENGINES
var arr = [["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos", "http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]];
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0;i<arr.length;i++) {
sel.options[i]=new Option(arr[i][0],arr[i][1]);
}
}
function startSearch(){
var searchString = document.searchForm.searchText.value;
if(searchString!==''){
var mySel = document.searchForm.whichEngine;
var finalLocation = mySel.options[mySel.selectedIndex].value;
finalLocation += encodeURIComponent(searchString);
location.href = finalLocation;
}
return false;
}
function checkKey(e){
var character=(e.which) ? e.which : event.keyCode;
return (character=='13') ? startSearch() : null;
}
I would also move your onload handler into the main body of your JavaScript:
window.onload = function() {
addOptions();
document.searchForm.searchText.focus();
};
I also made some changes to your HTML:
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="." onsubmit="return false;">
<input name="searchText" type="text" onkeypress="checkKey(event);" />
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select><br />
<input tabindex="2" type="button" value="Search"
onclick="startSearch();" />
</form>
</div>
</body>
You could specify which egine you would like preselected in the engines array like this:
// SEARCH ENGINES INIT
// I've used array literals for brevity
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
/*
* notice that this next line has an extra element which is set to true
* this is my default
*/
["Videos", "http://www.youtube.com/results?search_query=", true],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
Then in your setup function:
// SEARCH FORM INIT
function addOptions() {
var sel = document.searchForm.whichEngine;
for (var i = 0; i < arr.length; i++) {
// notice the extra third argument to the Option constructor
sel.options[i] = new Option( arr[i][0], i, arr[i][2] );
}
}
if your only concern is preselecting an engine onload, don't "over-engineer" it.
var Web = "http://www.google.com/search?q=";
var Images = "http://images.google.com/images?q=";
var Knowledge = "http://en.wikipedia.org/wiki/Special:Search?search=";
var Videos = "http://www.youtube.com/results?search_query=";
var Movies = "http://www.imdb.com/find?q=";
var Torrents = "http://thepiratebay.org/search/";
function addOptions(source){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
then insert your argument made onto your body tag to a pre-defined variable. If you want something random, create a new function with your equation for selecting a random variable then load your addOptions(function) within your new function. Then remove addOptions from your body tag.
<body onload="addOptions(Web);document.forms.searchForm.searchText.focus()">