I have a very simple form which is used to search for data on another website, The issue I am having now is how to return the query.
Here is my form
<form action="javascript:redirect()">
<label>Search :
<input id="search" type="search">
<select name="level" id="level1">
<option value="senior">Senior</option>
<option value="junior">Junior</option>
</select>
</label>
<button type="submit">Search website</button>
</form>
Here is my script:
<script type="text/javascript">
function redirect() {
var q = document.getElementById("search");
var level = document.getElementById("level");
var url = "https://someweb.com/search/?q=" + q.value;
window.open(url,"");
}
</script>
I want to return something like this
https://someweb.com/search/?q=search-id&level=levelid
ie. if i search for css and select junior, my browser should return
https://someweb.com/search/?q=css&level=junior
Build your level, then concat it to your url.
For example:
<script type="text/javascript">
function redirect() {
var q = document.getElementById("search");
var level = document.getElementById("level");
// Build level query string
level = level.value ? '&level=' + level.value : '';
var url = "https://someweb.com/search/?q=" + q.value + level;
window.open(url,"");
}
</script>
I have two html, first sends value to another. I want in second html receive data in javascript. On first html page user would be able to insert localhost:8888 address, address should be send to java script in another html...for now i have default address in java script .. please help.
first html
<form action="second.html" method="GET" >
<input type="text" name="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
second html
<script>
$(document).ready(function () {
var ws = new WebSocket("ws://localhost:8888/ws");
ws.onopen = function(evt) {
var conn_status = document.getElementById('conn_text');
conn_status.innerHTML = "Status: Connected!"
};
...
got more code
<script>
...
You can get submitted data from URL, because your from has submit method GET:
first html:
<form action="second.html" method="GET" >
<!-- In this way we can get submitted data from get param "host" -->
<input type="text" name="host" />
<input type="submit" value="Submit" />
</form>
second html:
<script>
$(document).ready(function () {
// function to get params from url
function getQueryParams(query) {
query = query || window.location.search;
if (query.length === 0) {
return {};
}
var params = {};
var paramsArr = query.split('&');
for (var i = 0; i < paramsArr.length; i++) {
var p = paramsArr[i].split("=");
params[p[0]] = p[1] || '';
}
return params;
}
// try to get param "host" from url (which submitted from first html)
var queryParams = getQueryParams();
var host = queryParams.host || 'localhost:8888';
var ws = new WebSocket('ws://' + host + '/ws');
ws.onopen = function (evt) {
var conn_status = document.getElementById('conn_text');
conn_status.innerHTML = "Status: Connected!"
};
// more code
}
</script>
I am VERY NEW to javascript and am messing around with some math. I currently have:
<input disabled="disabled" type="text" id="backer-prediction-answer" width="100" value="" />
<FORM>
<INPUT type="button" value="Apply" name="button1" onclick="apply()">
</FORM>
<script>
var backerPrediction1 = document.getElementById("backer-prediction-1").value;
var backerPrediction2 = document.getElementById("backer-prediction-2").value;
var backerPrediction3 = document.getElementById("backer-prediction-3").value;
var backerPrediction4 = document.getElementById("backer-prediction-4").value;
function apply(){
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
document.getElementById("backer-prediction-answer").value = (backers);
}
</script>
I would like to be able to hit apply and have it recalculate. Do I need to delete the variable before declaring it again? If so, how do I do that?
Move the variables backerPredictionX inside the function, so that they are evaluated everytime you apply()
<script>
function apply(){
var backerPrediction1 = document.getElementById("backer-prediction-1").value;
var backerPrediction2 = document.getElementById("backer-prediction-2").value;
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
document.getElementById("backer-prediction-answer").value = (backers);
}
</script>
With jquery (code not validated):
function apply(){
var backerPrediction1 = $("#backer-prediction-1").val();
var backerPrediction2 = $("#backer-prediction-2").val();
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
$("#backer-prediction-answer").val(backers);
}
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();
});
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()">