Greet User by name using Javascript and query string - javascript

I am trying to get the user's name from a form input and display it on the page in the form of a greeting "Hello (user)".
I have already got the solution to do it in 2 separate HTML files but I need to do it all in one file using query string and onload options.
Thanks for your help!
firstpage.html
<input type="text" id="titletxt">
<button onclick="Submit()">Submit</button>
<script>
function Submit() {
let name = document.getElementById("txtname").value;
window.location.href = "secondpage.html?" + name;
}
</script>
secondpage.html
<html>
<head>
<title>Test</title>
<script>
function loadTitle() {
let queryString = window.location.search.split('?')[1];
document.write("<h2>Hello "+queryString+"</h2>")
document.title = "hello "+queryString;
}
</script>
</head>
<body onload="loadTitle()">
</body>
</html>

Change your secondpage.html body to:
<body onload="loadTitle()">
<script>
function loadTitle() {
const queryString = window.location.search;
const name = new URLSearchParams(queryString).get("name");
document.body.innerHTML = "<h2>Hello " + name + "</h2>";
document.title = "hello " + name;
}
</script>
</body>

If I am correct in believing that you wanted all of the code to be in one file, I have a solution for you.
Solution with search params:
It simply checks if there is a search parameter called 'name' and if there is is replaces everything with Hello [name].
<html>
<head>
<title>Hello</title>
</head>
<body>
<input type="text" id="titletxt">
<button onclick="Submit()">Submit</button>
<script>
function loadTitle() {
const queryString = window.location.search;
const name = new URLSearchParams(queryString).get("name");
if (name) {
document.body.innerHTML = "<h2>Hello " + name + "</h2>";
document.title = "Hello " + name;
}
}
document.body.onload = loadTitle;
function Submit() {
let name = document.getElementById("titletxt").value;
window.location.search = "?name=" + name;
}
</script>
</body>
</html>

Related

Pass a variable from web app and display dialog

I am trying to pass a searchterm from a google web app to display the results. I am having trouble on submission I receive a blank screen. When the form is submitted, I would like it to display the results. The main code works within the logger- now I am just working on the UI and getting the form to work.
Any help is appreciated!
So far this is the code I have:
CODE:
function SearchFiles() {
//Please enter your search term in the place of Letter
var searchterm ="'mysearchinput'"; \\ this would be the variable that is passed from the form on index.html
var searchFor ="title contains " + searchterm;
var owneris ="and 'youremail#yourdomain.com' in Owners";
var names =[];
var fileIds=[];
var files = DriveApp.searchFiles(searchFor + owneris);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
fileIds.push(fileId);
var name = file.getName();
names.push(name);
}
for (var i=0;i<names.length;i++){
Logger.log(names[i]);
Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);
}
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function processForm(formObject) {
Logger.log('I was called!');
// here is where I would like to display results of searthterm.
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
}
function onFailure(error) {
var div = document.getElementById('output');
div.innerHTML = "ERROR: " + error.message;
}
</script>
</head>
<body>
Hello, World!
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input type="text" name="search">
<input type="submit" value="Submit" />
</form>
<input type="button" value="Close"
onclick="google.script.host.close()" />
SEARCH FUNCTION:
function SearchFiles() {
Logger.log('I Searched Files');
//Please enter your search term in the place of Letter
var searchterm ="'Whatevertextisinthesearchbox'";
var searchFor ="title contains " + searchterm;
var owneris ="and 'Youremail#yourdomain' in Owners";
var names =[];
var fileIds=[];
var files = DriveApp.searchFiles(searchFor + owneris);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
fileIds.push(fileId);
var name = file.getName();
names.push(name);
}
for (var i=0;i<names.length;i++){
// Logger.log(names[i]);
// Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);
var filesreturned = {
name:names[i],
urls:"https://drive.google.com/uc?export=download&id=" + fileIds[i]
}
Logger.log(filesreturned.name + " - " + filesreturned.urls);
return(filesreturned);
}
}
As per your comment above, here is the code to simply show hello world on button click. For your reference, I have also added a code to pass data between javascript and appscript.
Index.html file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function displayMessage()
{
google.script.run.withSuccessHandler(helloWorld).parseDataFromAppscript();
}
function helloWorld(stringText)
{
document.writeln(stringText);
}
</script>
</head>
<body>
<input type="button" value="submitButton" name="submitButton" onclick="displayMessage()"/>
</body>
</html>
Code.gs file
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate()
.setTitle('Hello World')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function parseDataFromAppscript()
{
return "Hello World!";
}
To run this, go to publish -> deploy as web app -> update. And then click latest code.
If you want explanation for any part, please feel free to ask. I'm assuming you already know html javascript and google.script.run method. :)

Passing javascript variable from one html page to another page

Hello All i started working on html recently,but iam struck in this situation where i want to send a value from one html page to the next html page just like,how websites shows our name after sign up success.Here i have written two html pages with,
pageOne.html
<!DOCTYPE html>
<head>
<title>
Home
</title>
<meta charset="UTF-8">
</head>
<style>
.myP{
color: lightgreen;}
</style>
<body>
<p id="p1" class="myP" onclick="myFun()">DataSend</p>
</body>
<script>
function myFun(){
document.getElementById("p1").style.color = "blue";
var textprevi=document.getElementById("p1").innerHTML;
localStorage.setItem("message", textprevi);
window.open("pageTwo.html","_self");
}
</script>
</html>
and my second
pageTwo.html
<!DOCTYPE html>
<html>
<body onload="fun">
<input type="text" id="tBox">
</body>
<script>
function fun()
{
document.getElementById("tBox").innerHTML = localStorage.getItem("message");
}
</script>
</html>
But when i tried the above solution,the element with id = "tBox" was empty but i wanted it to be filled with value = "DataSend" which is from pageOne.html.
Please help me with the promblem.
Thanks in advance.
The problem is with this line
document.getElementById("tBox").innerHTML = localStorage.getItem("message");
Here tBox is a an input element. So you have to use value instead of innerHTML
document.getElementById("tBox").value= localStorage.getItem("message");
You can do it using querystring parameters
In page one:
function myFun(){
document.getElementById("p1").style.color = "blue";
var textprevi=document.getElementById("p1").innerHTML;
window.open("pageTwo.html?data=" + textprevi,"_self");
}
In page 2
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var data = getParameterByName('data');
You made two mistakes in pageTwo.html.
<!DOCTYPE html>
<html>
<body onload="fun()"><!-- You didn't invoke the function here -->
<input type="text" id="tBox">
</body>
<script>
function fun()
{
document.getElementById("tBox").value = localStorage.getItem("message"); // You need to set the value for input fields, not innerHTML.
}
</script>
</html>
These changes should make your code work.

why there is no output

I wrote an example on Javascript function fiddle, but there is no output, how can I solve this mistake.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function student(name,id,level,phone){
var name, id, level, phone;
this.name= name;
this.id= id;
this.level= level;
this.phone= phone;}
function myFunction(){
var stud = new student("khaled al gamd","110_35_1353","three",0501607419);
var name= stud.(name);
var id= stud.(id);
var level= stud.(level);
var phone= stud.(phone);
document.write (name);
document.write (id);
document.write (phone);
}
<p id="result"><\/p>
document.getElementById("result").innerHTML=myFunction();
</script>
</body>
</html>
You need to write out that paragraph tag if you want to create it through JavaScript:
function student(name, id, level, phone) {
this.name = name;
this.id = id;
this.level = level;
this.phone = phone;
}
function myFunction() {
var stud = new student("khaled al gamd", "110_35_1353", "three", 0501607419);
var name = stud.name;
var id = stud.id;
var level = stud.level;
var phone = stud.phone;
return name + "<br>" + id + "<br>" + phone;
}
document.write('<p id="result"> </p>');
document.getElementById("result").innerHTML = myFunction();
For help on JavaScript, you can try JSHint:
http://jshint.com/
Your JavaScript with html together.
Try this:
<html>
<head>
</head>
<body>
<p id="result">
<script type="text/javascript">
function student(name,id,level,phone){
this.name= name;
this.id= id;
this.level= level;
this.phone= phone;
}
function myFunction(){
var stud = new student("khaled al gamd","110_35_1353","three",0501607419);
var name= stud.name;
var id= stud.id;
var level= stud.level;
var phone= stud.phone;
document.write(name);
document.write(id);
document.write(phone);}
myFunction();
</script>
</p>
</body></html>
The other answers here are correct, but neither of them explain why they are correct so here's a little explanation.
Here is a working version of your code:
<html>
<head>
</head>
<body>
<p id="result"></p>
<script type="text/javascript">
function student(name,id,level,phone){
var name, id, level, phone;
this.name= name;
this.id= id;
this.level= level;
this.phone= phone;
}
function myFunction(){
var stud = new student("khaled al gamd","110_35_1353","three",0501607419);
var name= stud.name;
var id= stud.id;
var level= stud.level;
var phone= stud.phone;
return name + id + phone;
}
document.getElementById("result").innerHTML=myFunction();
</script>
</body></html>
Now, there were a few issues with your example. Firstly, you were trying to access attributes of the student object like this: stud.(name) which is not valid syntax. The correct syntax for this is: stud.name.
Secondly, you were declaring html elements inside your script tags. Everything inside the script tags should be valid javascript, which this is not. You have two alternatives, one is to move that line outside the script tags (inside the body, above your script or it won't be created until after the script is run), the other is to create the elements with javascript as in the answer by #Emil S. Jørgensen.
Thirdly, you were trying to set the inner html of the element to the result of the function, but the function did not return anything to display. Rather it tried to write directly to the document. This will give you some output, but it will not be inside the element that you are aiming for. Instead what you need to do is to return some valid html from the function (although this does not necessarily have to contain any html elements).
Correct these issues and it should work as expected. One side note though, your code is not well formatted which makes it harder to read and harder to spot problems. I would suggest you take care in formatting your code in future.

document.getElementById returns null on a dynaimcally created div

Something weird is happening here.
My website is using javascript to create dynamic divs, but although they are entered into the DOM (at least this is what I think), javascript returns null when calling that div.
This is the javscript code which is loaded before </body>
function AddPlayer(){
var name = document.getElementById('name').value;
createBox(name);
};
function createBox(name){
var span = document.createElement('span');
span.id = name;
span.innerHTML = name;
document.getElementById("gameArea").appendChild(span);
var span = document.createElement('span');
span.id = "score-" + name;
span.innerHTML = "0";
document.getElementById("gameArea").appendChild(span);
var inputSText = document.createElement('input');
inputSText.type = "button";
inputSText.value = "Add Points";
inputSText.onclick = function(){AddPoints(name);};
document.getElementById("gameArea").appendChild(inputSText);
};
function AddPoints(player){
document.load(document.getElementById("#score-"+ player).innerHTML = "Please work");
};
<html>
<head>
<title>Game Score Keeper</title>
</head>
<body>
<h2>Game Score Keeper</h2>
<input type="text" id="name" />
<input type="button" value="Add Player" onclick="AddPlayer()" />
<div id="gameArea">
</div>
<script src="index.js"></script>
</body>
</html>
Here is the jsfiddle of this project http://jsfiddle.net/jwmm6rk7/
You need to pass the id of the element to document.getElementById. That is, without the hash (#) symbol.
function AddPoints(player) {
document.load(document.getElementById("score-" + player).innerHTML = "HELLO");
};
lookslike you were jQuery user, you used # and name instead of player
function AddPoints(player) {
document.getElementById("score-" + player).innerHTML = "HELLO";
};

Javascript opener window

I have function that opens up a window, and the values from the newly opened window are listed in the opener window.
The 2nd window - has this function:
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
opener.jQuery("#r_docs").append(jQuery(html));
}
The function that calls the one above is:
function addRefDoc(){
var count = 0;
var ref_docarray ;
var ref_noarray ;
<%for(int i1=0; i1<vec.size(); i1++) {
prop = (Properties) vec.get(i1);
String ref_no = prop.getProperty("referral_no","");
String ref_name = (prop.getProperty("last_name", "")+ ","+ prop.getProperty("first_name", ""));
%>
if(document.getElementById("refcheckbox_<%=ref_no%>").checked) {
count++;
if ((ref_doctor!=null)&&(ref_doctor!="")&&(ref_docno!=null)&&(ref_docno!="")) {
ref_docarray = ref_doctor.split(";");
ref_noarray = ref_docno.split(";");
if ((containsElem(ref_docarray,"<%=ref_name%>"))||(containsElem(ref_noarray,<%=ref_no%>))) {
alert("Referral doctor " + "<%=ref_name%>" + " already exists");
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
}
<%} %>
self.close();
}
function containsElem(array1,elem) {
for (var i=0;i<array1.length;i++) {
if(array1[i]==elem){
return true;
} else{
return false;
}
}
}
When this function is called, it is supposed to carry the 2 input elements "ref_docs" and "ref_nos" into the page that opened this window. But it is not doing so. It lists the elements alright but when I try to use "ref_docs" and "ref_nos" in another Javascript function in the 1st window, I see that "ref_nos" and "ref_docs" are empty.
What am I doing wrong?
function updateRd(){
var ref_docs = jQuery("#updatedelete").find('input[name="ref_docs"]');
var ref_nos = jQuery("#updatedelete").find('input[name="ref_nos"]'); alert(ref_docs.val() + ref_nos.val());
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";")); }
–
This function returns an error saying "ref_docs" and "ref_nos" are undefined.
I think it is trying to use the jQuery on the other page to find "#r_docs" on the current page.
Try:
jQuery(opener.document).find("#r_docs").append(html);
UPDATE:
I created index.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
window.jQuery = jQuery;
function openChild ()
{
var mychildwin = window.open("child.html");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="openChild();" />
<div id="r_docs">
Redocs here.
</div>
</body>
</html>
and child.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="AddOtherRefDoc('name', 42);"/>
</body>
</html>
UPDATE2:
in your update function document.updatedelete has no attributes ref_docs and ref_nos.
try:
jQuery("#updatedelete")
.find('input[name="ref_docs"], input[name="ref_nos"]')
Where your form is
<form id="updatedelete" ... >
Your function that accesses the DOM elements is incorrect. updatedelete is not a property of document, nor will accessing a ref_docs or ref_nos property automatically build a collection of input elements. Since you're using jQuery already, try this:
var ref_docs = $('input[name="ref_docs"]');
var ref_nos = $('input[name="ref_nos"]');
That will give you Array (or at least array-like) objects that will let you access your inputs:
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";"));

Categories

Resources