I would like to integrate the Google Search bar into my site, and using the default code by Google CSE I have:
<div id="cse-search-form" style="width: 100%;">Loading</div>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function() {
var customSearchOptions = {};
var imageSearchOptions = {};
imageSearchOptions['layout'] = google.search.ImageSearch.LAYOUT_POPUP;
customSearchOptions['enableImageSearch'] = true;
customSearchOptions['imageSearchOptions'] = imageSearchOptions;
var customSearchControl = new google.search.CustomSearchControl(
'003243520079760326318:WMX-1462312306', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setSearchFormRoot('cse-search-form');
options.setAutoComplete(true);
customSearchControl.draw('shop.htm/cse', options);
}, true);
Followed by the style and the </div>
But I do not want the results to open on the same page, I want them to open in searchresults.htm which has the container div
<div id="cse" style="width:100%;"></div>
if I put in this form:
<form action="http://www.amberantiques.com/searchresults.htm" id="cse-search-box">
<fieldset style="border:none;">
<input type="hidden" name="cx" value="003243520079760326318:WMX-1462312306" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" size="31" />
<input type="submit" name="sa" value="Search" />
</fieldset>
</form>
Then the form sends it to the page but doesnt run the search, but if you then use the Google bar on the page, it runs the search fine.
Basically, how do you get the google bar to open the results page?
Cheers
If you upgrade to the latest Google Code V2 then you can achieve this by editing code you paste to show results.
<gcse:search></gcse:search>
Change this to
<gcse:search linktarget="_parent"></gcse:search>
When you're building the code for your Google CSE, one of the Look and Feel options is "Two Page" - which will allow you to search on one page, and display the results on another.
The V2 code for the Custom Search (free) or Site Search (paid) gives you a range of options for searching and displaying results on the same page or having it's own result page.
By default this WILL open all result links in a new tab or window.
I had the issue where I needed the search results to open on the same tab/window.
I adjusted the following code
<gcse:search></gcse:search>
to this
<gcse:search linktarget="_self"></gcse:search>
I guess if for some reason your default behavior is not opening in a new tab/window and you need it to then you could try the following
<gcse:search linktarget="_blank"></gcse:search>
Hope this helps.
Can you test by putting this code?
options.enableSearchboxOnly("http://www.amberantiques.com/searchresults.htm");
between this line
var options = new google.search.DrawOptions();
and this line
options.setSearchFormRoot('cse-search-form');
Then put the following code in searchresults.htm
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
function parseQueryFromUrl() {
var queryParamName = "q";
var search = window.location.search.substr(1);
var parts = search.split('&');
for (var i = 0; i < parts.length; i++) {
var keyvaluepair = parts[i].split('=');
if (decodeURIComponent(keyvaluepair[0]) == queryParamName) {
return decodeURIComponent(keyvaluepair[1].replace(/\+/g, ' '));
}
}
return '';
}
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function () {
var customSearchControl = new google.search.CustomSearchControl(
'003243520079760326318:WMX-1462312306', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
var queryFromUrl = parseQueryFromUrl();
if (queryFromUrl) {
customSearchControl.execute(queryFromUrl);
}
}, true);
</script>
If this doesn't work you can simply read the documentation provided by google. You'll get your desired information in Designing the Look and Feel with the Control Panel section. Or you may find it in Designing the Look and Feel with XML section. I think you are looking for two page layout.
Another option is to go to http://www.google.com/cse/manage/all and then use the control panel there to customize your search engine as you desire.
Building on the code above, you could use:
<gcse:search newWindow="true"></gcse:search>
According to Google's documentation.
Not obvious from looking at the Google documentation (a familiar story) but you can do this very simply using the v2 Custom Search code by selecting the 'Results only' option in the 'Look and Feel' section:
Click 'Save and Get Code' and paste into your searchresults.htm page.
You now just need to create a simple search box that points to that page which you can put in your page header.
e.g.
<form action="http://www.amberantiques.com/searchresults.htm">
<input type="search" name="q"/>
<input type="submit" value="Go"/>
</form>
Related
So this is my first question. I'm very new to coding, and only have done a few basic programs, so please don't judge me if the answer is obvious. Me and my friend have worked together to create a chat app. We are currently making a password for the program because right now, anyone with the url can join. I am already aware of <input type="password> and I have made a little program using it, but what I want to do is to make this code more secure/make other code appear and the button and password disappear. (This is the program I was talking about)
<!DOCTYPE html>
<html>
<body>
<script>
function pswChecker(){
var psw = document.getElementById("psw").value;
if(psw == "password") {
alert("Code goes here.");
} else {
window.close();
}
}
</script>
<div class="fadeMe">
<div>
<div style="color=white;">What is the password?</div>
<input type="text" id="psw" name="psw">
<input type="button" value="Submit" id="submit" onClick="pswChecker()">
</div>
</body>
</html>
Keeping your password inside of HTML source is not secure and everyone who can access your website can see the password. Since you are working on a chat application I assume you have some sort of a server - you will have to perform checks on the back end.
To hide an element you can add an ID to it and use the following code:
const passwordDiv = document.getElementById("password");
const hideButton = document.getElementById("hide");
hideButton.addEventListener("click", function () {
passwordDiv.style.display = 'none';
});
<div id="password">
The password form goes here.
<button id="hide">Hide</button>
</div>
If you want to show something else you can use the same code but set the display to block instead.
To add a style which is what I think you want you can do something like this.
document.getElementsByClassName("fadeMe").style.display = "none";
I came across the following script last night and it works really nicely to drop files into a Google Drive folder, however I've noticed that there's no clear way to get back to the front page of the app after uploading a file.
https://script.google.com/macros/d/1URDuve8yT1EpDj_WKLHPAuiVt1LWDdUN2kzH-ERUnuxVQqXbi-9I9EfU/edit?usp=drive_web
I realised that this can be achieved by refreshing the page, but my end users are people who are not very computer savvy, and I would like to add a button that refreshes the form to make it a bit easier on them. Unfortunately, I have no idea how to go about doing this.
Can anybody help me out?
Once your file is uploaded successfully this function is called :
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
As we can see, this function is hiding the form and putting status in output div, so if we don't hide the form and only update status in output[or maybe you can so a popup/alert on success ?] I think your purpose will be solved.
Something like this should work [Maybe you'll need to style your html a bit]:
function fileUploaded(status) {
document.getElementById('output').innerHTML = status;
}
You can add a button with href to the self page[web app], this is a hacky way to refresh.
The form is has id="myForm" and the status is shown on a div with id="output".
To show the form set is display style property to block. You could do this my using something like
document.getElementById('myForm').style.display = 'block';
To clear the status just add use something like
document.getElementById('output').innerHTML = '';
Example:
The following examples use HTML/CSS and pure JavaScript to show how to "reset a page" on Google Apps Script
//Initializes the html elements as they are shown after a file is uploaded
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = "File uploaded successfully.";
function resetPage() {
document.getElementById('myForm').style.display = 'block';
document.getElementById('output').innerHTML = '';
}
input {
display:block; margin: 20px;
}
<form id="myForm">
<input type="text" placeholder="Input 1">
<input type="text" placeholder="Input 2">
</form>
<div id="output"></div>
<input type="button" onClick="resetPage();" value="Reset">
Hey guys i was wondering how to acquire information from form in javascript and i found the method with object forms, but i doesnt want to work(returns undefined), because object is undefined. Do you know what i am doing wrong in that, could you attach some explanations? I know what it is possible to do it by getElement function,but i would like to understand why this solution doesn't work.
Regards!
<script type="text/javascript">
function cos(sth){
var par = document.getElementById("para1");
par.style.color = 'blue';
par.style.fontSize="30px";
par.style.fontFamily="Impact,Charcoal,sans-serif";
}
function getFormValue(){
document.write(5+6);
var doc = document.forms["myForm"]["email"].value;
// OR
var doc = document.forms[0].elements["name"];
document.write(doc);
}
</script>
</head>
<body>
<p id ="para1">JavaScript Exercises - w3resource</p>
<div>
<button onclick="cos();">Style</button>
</div>
<form name="myForm">
<input type="text" name="email"/>
<button onclick="getFormValue()">
</form>
</body>
</html>
document.write(5+6);
var doc = document.forms["myForm"]["email"].value;
Since the page has loaded, the document is in a closed state.
Calling document.write implicitly calls document.open which creates a new document.
You then write 11 to this document.
Next you try to get the form element. It doesn't exist in this new document.
Then you try to get the email field from it. Since you don't have a form, you get an error.
If you fix that:
var doc = document.forms["myForm"]["email"].value;
// OR
var doc = document.forms[0].elements["name"];
document.write(doc);
You read the value of the email field and assign it to doc.
Then you overwrite it with elements["name"].
There is no form control called name, so you get undefined.
var doc = document.forms["myForm"]["email"].value;
document.write(doc);
… works fine. You just need to remove the junk you put around it to break it.
I have a problem with json. I'd like to display the result of my form in the new browser window in JSON. (When user fills all fields in the form, button becomes enabled and shows JSON in specified format (I did it)). I translated it in JSON but dunno how to output it...I'm thinking of create new html page and do window.open on button on 1st page, but then it doesn't read data from 1st page which user entered. Or should I save it somehow in JSON file and then read it from other page?
For example:
<form name="form" ng-controller="MyCtrl">
<label> <b> * Date: </b> </label> <input type="datetime-local" ng-model="date" name="date" onkeyup="changeButtonStatus()" onchange="changeButtonStatus()" required> </input>
<button type="submit" id="btn" class="btn" disabled="disabled">Submit</button>
</form>
I have some form with date field and button:
I can easily get JSON of date field by {{date | json}} on the same page, but I just want to output it in new browser window. How can I do this? Please help me with some tips. Thanks.
If it's not too big you can send the information to the new window as a data URL.
The frame will be reused once it is open.
This might be a start, showing how to plug in the JSON data and break it up over multiple lines for display.
window.open('data:application/json,'
+JSON.stringify(location).replace(/([[{,])/g, "$1%0a"),
'jsonFrame',
'resizeable,top=100, left=100, height=200, width=300,status=1')
See MDN for all the details.
You should be able to get at the window.opener from the new window and parse values out of it. The following plunker shows storing data from the current scope in an accessible area when the controller's submit is clicked. From the new window it then parses the content from the opener into the window's scope for further processing.
http://plnkr.co/edit/OkKX5zxYVSoZ7w81WV8J?p=preview
You'll notice here too how to get an angular friendly way of calling the submission and the disabling of the button until ready.
Hope this helps.
How about to save your input data into a cookie on one page and then get it via JavaScript when you will open a new window?
I could prepare the code in jsFiddle, but seems like it does not import external resources at this moment. So I'll post it here:
page 1:
...
<form name="form" ng-controller="MyCtrl">
<label> <b> * Date: </b> </label> <input id="date" type="datetime-local" ng-model="date" name="date" onkeyup="changeButtonStatus()" onchange="changeButtonStatus()" required> </input>
<button id="btn" class="btn" >Submit</button>
</form>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
$('#btn').click( function() {
var cookie_value = $('#inut_test').val();
/*cookie_value should be your json string*/
$.cookie("json_cookie", cookie_value, { path: '/' });
window.open("http://localhost/page2");
return false;
});
</script>
...
page 2:
...
<a id="see-cookie" href="#">
click me!!!
</a>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
$('#see-cookie').live('click', function() {
alert($.cookie('json_cookie'));
return false;
});
</script>
...
Do not forget about { path: '/' } cookie property to set it for all site and about including jQuery cookie library into your page.
I am attempting to build a UI for a spreadsheet using GAS HtmlService. The HTML below is a very simple form with a single text box that pulls a value ("Kristina") from the sheet, successfully. However, when I try to submit the form a new tab is opened in Chrome that attempts to open the URL "bffc95ee-ff64-4d2c-xxxx-19d9824eb4b4.foo.bar/?fname=Kristina" with "xxxx" replacing more random letters and numbers (just in case). At no point do I use the words "foo.bar" in my code, so I'm pretty sure that that part isn't coming from me. It does not change each time or after logging out and back in. I'm getting the same result on two different computers.
<html>
<body>
<div>
<form id="formtest1">
<label>First Name</label>
<input name="fname" type="text" maxlength="255" value="<?= fname ?>"/>
<input type="submit" value="Submit"
onclick="google.script.run.processForm(document.getElementById('formtest1'));
google.script.host.close()"/>
</form>
</div>
</body>
</html>
The above is being displayed using the following function:
function htmltest(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sht = ss.getActiveSheet();
var html = HtmlService.createTemplateFromFile("HTML");
html.fname = sht.getRange(2, 3).getValue();
ss.show(html.evaluate());
};
If I understand correctly, the "google.script.run.processForm(...)" script in the HTML should trigger the following function, as set up in the projects triggers:
function onFormSubmit(){
Browser.msgBox("Test");
};
But it doesn't appear to do so as the form doesn't close and the msgBox doesn't appear. Only the foo bar URL in a new tab.
Hopefully I've explained the issue clearly and am not making an embarrassing mistake.
You cannot use a real "submit" button with google.script.run (this is a documented restriction in the user guide). Change it to "button" and it should work fine.
The project trigger onFormSubmit() will be triggered by a submission via the Forms Service. There is no relationship between this trigger and your HTML code; they are two different ways to interact with users.
An html forms pattern is shown in the HTML Service documentation here, and the script below is an adaptation of it.
Code.gs
The only real change from your original is that onFormSubmit() has been replaced with processForm(form), which includes a parameter, for the object that will be passed from the html code.
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "htmltest",
functionName : "htmltest"
}];
sheet.addMenu("Custom Menu", entries);
};
function htmltest(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sht = ss.getActiveSheet();
var html = HtmlService.createTemplateFromFile("HTML");
html.fname = sht.getRange(2, 3).getValue();
//Logger.log( html.getCodeWithComments() );
ss.show(html.evaluate());
};
function processForm(form){
var fname = form.fname;
Browser.msgBox("Test - " + fname);
};
HTML.html
This is a modification of your original, echoing the pattern from the documentation. The form submission SuccessHandler is a one-liner, which closes the dialog. Once it completes, the server-side function is invoked with the form content, retrieved using this.parentNode (to refer to the form).
There are other ways - see Get value of html text box in Apps Script function for a different approach.
<html>
<script type="text/javascript">
// SuccessHandler to close form
function close() {google.script.host.close();}
</script>
<body>
<div>
<form>
<label>First Name</label>
<input name="fname" type="text" maxlength="255" value="<?= fname ?>"/>
<input type="button" value="Submit" onclick="google.script.run
.withSuccessHandler(close)
.processForm(this.parentNode)"/>
</form>
</div>
</body>
</html>
Just add this to your script tag on your html file.
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
Source: HTML Service: Communicate with Server Functions