I'm in the process of creating a small currency conversion script using the money.js library and have run into a problem with the .append(); part. Here is what I have so far:
<script type="text/javascript">
$(document).ready(function () {
function pfxCurrencyConverter() {
//get the users options from the form and store in variables
var pfxFromCurrency = $('#pfx-from-currency').val();
var pfxToCurrency = $('#pfx-to-currency').val();
//set base options
fx.base = pfxFromCurrency
fx.settings = {
from: pfxFromCurrency
};
// get the amount input by the user
var inputAmount = $('#pfx-input-amount').val();
// Load exchange rates data via the cross-domain/AJAX proxy:
$.getJSON('http://openexchangerates.org/latest.json', function (data) {
// Check money.js has finished loading
if (typeof fx !== "undefined" && fx.rates) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates: data.rates,
base: data.base
}
}
var convertedValue = fx.convert(inputAmount, {to: pfxToCurrency});
$("#currencies").append("<li>New Value" + convertedValue + "</li>");
});
} //end pfxCurrencyConverter
$(document).ready(function () {
pfxCurrencyConverter();
});
</script>
</head>
<!-- output form for user to populate -->
<!-- Output the front end form, include external stylesheet and define customisable css -->
</head>
<!-- output form for user to populate -->
<body>
<form method="get" onsubmit="return pfxCurrencyConverter();">
Amount: <input type='text' id='pfx-input-amount' /><br />
From: <select id='pfx-from-currency'>
<option>Please Choose</option>
<option>GBP</option>
</select><br />
To: <select id='pfx-to-currency'>
<option>Please Choose</option>
<option>USD</option>
</select><br />
<input type='submit' value='Convert' />
</form>
<ul id="currencies"></ul>
</body>
</html>
I have also this in the html right after the submit button, it works fine with just a string but stops working once I add + convertedValue
<script>document.write("New Value" + convertedValue);</script>
Any help is greatly apprecited
The problem was that the .append() was being called before the value was returned from getJson(). Placing the .append() inside the .getJson() solved the problem. This works:
<!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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://josscrowcroft.github.com/money.js/money.js"></script>
<script type="text/javascript">
function ConvertMoney(to, from, amt) {
// Load exchange rates data via the cross-domain/AJAX proxy:
$.getJSON('http://openexchangerates.org/latest.json',
function (data) {
// Check money.js has finished loading:
if (typeof fx !== "undefined" && fx.rates) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates: data.rates,
base: data.base
};
}
var result = "<li>" + fx.convert(amt, { from: from, to: to }) + "</li>";
$("#result").append(result);
});
}
$("#convert").live("click", function () {
var from = $("#pfx-from-currency").val();
var to = $("#pfx-to-currency").val();
var amt = $("#pfx-input-amount").val();
ConvertMoney(to, from, amt);
});
$(document).keypress(function(e) {
if(e.keyCode == 13) {
var from = $("#pfx-from-currency").val();
var to = $("#pfx-to-currency").val();
var amt = $("#pfx-input-amount").val();
ConvertMoney(to, from, amt);
}
});
</script>
</head>
<body>
Amount:
<input type='text' id='pfx-input-amount' /><br />
From:
<select id='pfx-from-currency'>
<option>Please Choose</option>
<option>GBP</option>
</select><br />
To:
<select id='pfx-to-currency'>
<option>Please Choose</option>
<option>USD</option>
</select><br />
<input type='button' id="convert" value='Convert' />
<ul id="result">
</ul>
</body>
</html>
Looks like you have an object terminated by a semicolon
var convertedValue = fx.convert(inputAmount, {to: pfxToCurrency; });
that is not valid, try changing it to
var convertedValue = fx.convert(inputAmount, {to: pfxToCurrency });
Also I would expect
var pfxToCurrency = document.getElementById('pfx-to-currency').value
and not just
var pfxToCurrency = document.getElementById('pfx-to-currency')
Looks like you have an extra <script> tag:
<script type="text/javascript">
$(document).ready(function(){
<script type="text/javascript">
please make sure that properly Closing your Document ready function ( ** closing )
$(document).ready(function () {
........
..........
});
} //end pfxCurrencyConverter
**});**
$(document).ready(function(){
pfxCurrencyConverter();
});
Related
I need to publish exam result from a Google sheet. The search button shows the marks obtained perfectly if roll no is provided at the box but I need to omit the fields with no value like Subject 3, 5 etc. with their textbox from the html page
Here is the sheet I'm using and the code I'm using ...
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
//Search for the id and return the array for that row
function search(id) {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/16IH3yKJjLwM9XA0c4_BN5MVQSKh8hV7gR6_kLLfe8to/edit#gid=0");
var sheet = ss.getSheetByName("Sheet1");
var values = sheet
.getDataRange()
.getValues()
.filter(function(row) {
return row[0] == id;
});
return values[0];
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
.hidden {
display:none;
}
</style>
</head>
<body>
<input type="text" id="txtName"/>
<button id="show">SHOW</button>
<h1>FMATS</h1>
Name <input type="text" id="name"/><br>
Roll <input type="text" id="roll"/><br>
Subject 1 <input type="text" id="sub1"/><br>
Subject 2 <input type="text" id="sub2"/><br>
Subject 3 <input type="text" id="sub3"/><br>
Subject 4 <input type="text" id="sub4"/><br>
Subject 5 <input type="text" id="sub5"/><br>
</body>
<script>
//When click on show button it will run search function
window.onload = function(e){
document.getElementById('show')
.addEventListener('click', search);
}
//Get the value for txtName input and run search function in code.gs
function search() {
var txtName = document.getElementById('txtName').value;
google.script.run.withSuccessHandler(fillInfo).withFailureHandler(function (e) { console.log(e) }).search(txtName);
}
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(values) {
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
for (var i=0;i<values.length-2;i++) {
if (values[i+2]==null) {
toggleElement("sub"+i);
} else {
document.getElementById("sub"+i).value = values[i+2];
}
}
//rest of the code here
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
document.getElementById('sub1').value = values[2];
document.getElementById('sub2').value = values[3];
document.getElementById('sub3').value = values[4];
document.getElementById('sub4').value = values[5];
document.getElementById('sub5').value = values[6];
}
</script>
</html>
I need to omit the Subject name and the text box with no value from the HTML page. And "Nothing Found" should be shown if a roll searched which is not in the table. It's not required but will be good if the Subject names come from sheet's row 1.
What should I do?
There are two ways to go about this:
Create your HTML on the server side (as #Cooper said)
Manipulate your HTML with JavaScript
To create your HTML on the server side you can use string and "write" the html automatically.
Then your functions will be something like this:
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(response) {
document.getElementById("divid").innerHTML=html
});
If you absolutely want to manipulate the HTML on the client-side, you will use something like this:
function toggleElement(id) {
var td = document.getElementById(id).parentElement;
var tr = td.parentElement;
tr.classList.toggle("hidden");
}
the usage is like so:
function fillInfo(values) {
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
for (var i=0;i<values.length-2;i++) {
if (values[i+2]==null) {
toggleElement("sub"+i);
} else {
document.getElementById("sub"+i).value = values[i+2];
}
}
//rest of the code here
}
and then you will have some css that does this:
.hidden {
display:none;
}
Edit:
This is how you implement the first solution:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="text" id="txtName"/>
<button id="show">SHOW</button>
<h1>FMATS</h1>
<div id="dataDiv"></div>
</body>
<script>
//When click on show button it will run search function
window.onload = function(e){
document.getElementById('show')
.addEventListener('click', search);
}
//Get the value for txtName input and run search function in code.gs
function search() {
var txtName = document.getElementById('txtName').value;
google.script.run.withSuccessHandler(fillInfo).withFailureHandler(function (e) { console.log(e) }).search(txtName);
}
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(values) {
console.log(values);
document.getElementById("dataDiv").innerHTML=values
}
</script>
</html>
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
//Search for the id and return the array for that row
function search(id) {
var ss = SpreadsheetApp.openByUrl("SHEETS URL");
var sheet = ss.getSheetByName("Sheet1");
var values = sheet
.getDataRange()
.getValues()
.filter(function(row) {
return row[0] == id;
})[0];
var legends = sheet.getRange(1,1,1,sheet.getMaxColumns()).getValues()[0];
return createHTML(legends, values);
}
function createHTML(legends, values) {
Logger.log(legends);
var htmlResult = "";
for (var i=0; i<values.length; i++) {
if (values[i]!=null && values[i]!=="") {
htmlResult += '<div class="field">' + (legends[i]+"").replace("Sub", "Subject ") + '<input type="text" id="sub1" value="'+values[i]+'"></div>';
}
}
return htmlResult;
}
Hope this helps!
Here's a simple example of a complete solution of your problem done mostly server side.
I like do it this way because I like to be able to use Utilities.formatString().
Server Functions:
File: aq3.gs:
function search(sObj) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet1');
var rg=sh.getDataRange();
var vA=rg.getValues();
var hA=vA[0];
var dObj={dA:[]};
for(var i=1;i<vA.length;i++) {
if(vA[i][0]==sObj.roll) {
var row=vA[i];
for(var j=0;j<hA.length;j++) {
dObj[hA[j]]=row[j];
}
break;
}
}
var html="<style>input{margin:2px 5px 0 2px}</style>";
for(var i=0;i<row.length;i++) {
if(dObj[hA[i]]) {
html+=Utilities.formatString('<br /><input id="txt-%s" type="text" value="%s" /><label for="txt-%s">%s</label>',i,dObj[hA[i]],i,hA[i]);
}
}
sObj['results']=html;
return sObj;
}
Run the below function to get the dialog running. The enter the roll you wish to see in the search box and click the search button. You will get only the boxes that have data.
function launchExamResultsSearchDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('aq5');
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Exam Results");
}
The html:
File: aq5.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function search() {
var text=$('#srchtext').val();
google.script.run
.withSuccessHandler(function(sObj) {
document.getElementById("results").innerHTML=sObj.results;
})
.search({roll:text});
}
console.log("My Code");
</script>
</head>
<body>
<input type="text" id="srchtext" /><input type="button" value="Search" onClick="search();" />
<div id="results"></div>
</body>
</html>
This is what the dialog looks like:
You can just keep changing the search roll number and the dialog will replace the data with the new data. You can control the subjects by changing the headers.
Client To Server Communication
Utilities.formatString()
I did not forget to add name attributes as is a common problem and yet my serialized form is returning an empty string. What am I doing wrong?
HTML/javascript:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$( document ).ready( function() {
$('#word_form').submit(function(e) {
e.preventDefault();
console.log($(this).serialize()); //returns an empty string
});
});
</script>
</head>
<body>
<div id="wrapper">
<form name="word_form" id="word_form" method="POST">
<input type="image" name="thumbsUp" id="thumb1" value="1" src="http://upload.wikimedia.org/wikipedia/commons/8/87/Symbol_thumbs_up.svg" style="width:50px;height:50px;">
<input type="image" name="thumbsDown" id="thumb2" value="2" src="http://upload.wikimedia.org/wikipedia/commons/8/84/Symbol_thumbs_down.svg" style="width:50px;height:50px;">
</form>
</div>
</body>
dont know if this is a better way, but you could write your own plugin for this, something like:
(function($) {
$.fn.serializeAll = function() {
var toReturn = [];
var els = $(this).find(':input').get();
console.log("Elements:" + els);
$.each(els, function() {
if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type) || this.src)) {
var val = $(this).val();
toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
}
});
return toReturn.join("&").replace(/%20/g, "+");
}
})(jQuery);
//and use it
var serialized = $('#word_form').serializeAll();
console.log(serialized);
Demo jsFiddle
I am trying to get the initials (upper case letters) of the name that the user enters inside the text field. I get and error that my function getInitials() is not defined. Why do I get this error? Also I want to check if the function exists with typeof.
<!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>Second task HS</title>
</head>
<body>
<form name="myForm" id="eForm" action="#">
<label for="name">Name</label>
<input type="text" id="name" name="fullname"/><br>
<input name="button" type="button" value="Pick" onclick="getInitials();"/>
</form>
<div id="result">
</div>
<script type="javascript">
var nameInput = document.getElementById('name').value;//I need to stringify the input and use it!
var arr, nameArr, first, last;
nameArr = name.split(' ');
first = nameArr[0][0].toUpperCase();
last = nameArr[nameArr.length - 1][0].toUpperCase();
if(typeof getInitials == 'function'){
function getInitials(nameArr) {
return {first: first, last: last};
}
getInitials(nameInput);
}else{
alert('Check getInitials!');
}
</script>
</body>
</html>
From what I see, you are checking if the function exists... before creating it !
Try rather this JS code :
function getInitials( nameInput ) {
var nameArr = nameInput.split(' ');
return {
first: nameArr[0][0].toUpperCase(),
last: nameArr[nameArr.length - 1][0].toUpperCase()
};
}
function getInitialsFromInput() {
var nameInput = document.getElementById('name').value;
if(getInitials instanceof Function){ //strictly speaking, useless because it is obviously a function
alert(getInitials(nameInput));
}else{
alert('Check getInitials!');
}
}
getInitialsFromInput() ;
(and use "getInitialsFromInput()" for the onclick to gather the input's value)
You missed the text in <script type="javascript">, the statement should be like this <script type="text/javascript">
Here is the simple version of what you wanted, try it, this program expects first name Or first and last name only.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Second task HS</title>
<script type="text/javascript">
var arr, first, last;
function getInitials() {
var nameInput = document.getElementById('name').value; //I need to stringify
nameArr = nameInput.split(' ');
if(nameArr.length > 1){
first = nameArr[0].toUpperCase();
last = nameArr[1].toUpperCase();
}else{
first = nameInput.toUpperCase();
}
var result = {first: first, last: last};
alert(result.first);
alert(result.last);
}
</script>
</head>
<body>
<label for="name">Name</label>
<input type="text" id="name" name="fullname"/><br>
<input name="button" type="button" value="Pick" onclick="getInitials()"/>
<div id="result">
</div>
</body>
</html>
Your code makes no sense. getInitials Just is not assigned initially, so the inline click handler within the button will never work.
If you need the input value with first characters uppercased and initials, try something like:
document.querySelector('button[value=Pick]').onclick = getInitials;
function getInitials(e) {
var value = document.querySelector('#name')
.value.split(/\s+/)
.map( first2Upper );
if (value[0].length){
var ret = {first: value[0],
last: value[1],
initials: value[0][0] +(value[1] && value[1][0] || '')};
document.querySelector('#result').innerHTML =
value.join(' ') + ' (initials: '+ret.initials+')';
return ret;
} else {
alert('please enter a value');
}
}
function first2Upper(str) {
return str.slice(0,1).toUpperCase() + str.slice(1);
}
Here's a mockup in jsFiddle
I'm beginning to use Jquery and I have the following JS function I would like to make with jquery
Anyone to help?
<script type="text/javascript" language="javascript">
function redirect() {
//var dest = "?phone=" + phone;
var prefill = "&prefill=3";
var info=document.choice.infos.value;
var dest = "&info="+info;
var url=document.choice.centres.value;
var urlfinal=url+dest+prefill;
document.location.href=urlfinal
}
</script>
<form name="choice">
<select name="centres">
<option value="http://toto.com/?var=1">var1</option>
<option value="http://toto.com/?var=2">var2</option>
</select>
<br />
<INPUT TYPE="text" NAME="infos">
<input type="button" value="Go!" onClick="redirect();">
</form>
Your button markup
<input type="button" value="Go!" id="submit">
and jquery code:
$(document).ready(function() {
$('#submit').click(function() {
//var dest = "?phone=" + phone;
var finalUrl = $("select#centers").val();
var querystring = '&prefill=3' + '&info='
+ $("select#info").val() + dest;
finalUrl = finalUrl + querystring ;
window.location.replace(finalUrl);
});
});
Use Google Chrome or Firefox with the Javascript console open and get in the habit of using console.log to check your code at critical points.
By the way, you don't need a form element:
...
<script type="text/javascript">
$(function () {
$('#btnRedirect').click(function () {
var centres = $('#centres');
var centre = $('option:selected', centres);
//console.log(centre.val());
var infos = $('#infos');
//console.log(infos.val());
var dest = "&info=" + infos.val();
var prefill = "&prefill=3";
var urlfinal = centre.val() + dest + prefill;
//console.log(urlfinal);
document.location = urlfinal;
});
});
</script>
...
<body>
<select id="centres">
<option value="http://toto.com/?var=1">var1</option>
<option value="http://toto.com/?var=2">var2</option>
</select>
<br />
<input type="text" id="infos"/>
<input id="btnRedirect" type="button" value="Go!"/>
</body>
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()">