Get URL parameter and prefill form field - javascript

This is how the raw HTML of my form (email) field:
<input type="text" id="FormField_EmailAddress" name="email" value="" size="40">
Now I want to prefill this field based on the URL parameter email like for example mydomain.com/page/?email=my#email.com should prefill my#email.com.
By just using a script in the header or footer of that page.
Is that possible and can anybody share a way how to do it?
PS As a total beginner I tried:
<script>
var url_string = window.location.href;
var url = new URL(url_string);
var email = url.searchParams.get("email") ? url.searchParams.get("email") : '';
document.getElementsByName("email")[0].value = email;
</script>
but it won't work...

Finally, I made it, this is the code that made it work:
<script>
const url = window.location.search;
const urlParams = new URLSearchParams(url);
const email = urlParams.get('email');
document.getElementById('FormField_EmailAddress').value = email;
</script>

Related

Preview Email Template based on drop down, Send email once your satisfuied

in my Google Sheets app script, I currently have three template.html files and a few scripts; I'd like to create a preview email and send it to the user once he or she is satisfied; however, the event listeners that (openAI) built for me do not work; when I change the Drop Down Menu or click send Button, nothing happens and the preview does not load. When I ask the AI for help, it keeps modifying my code; My code no longer looks like the original; after a week of trying, I've realized that I need assistance with this. Here's my most recent code as of today. The AI also insisted on using Google Drive, which I declined because I have the HTML files in the app scrip sheet itself and used to obtain it with this.
This code is not used anymore, But use to work when I used it in GmailApp to get the template File Name.
var html = HtmlService.createTemplateFromFile('Proposal Template.html');
var html = HtmlService.createTemplateFromFile('Marketing Template.html');
var html = HtmlService.createTemplateFromFile('Trusted Partner Template.html');
Keep in mind that while I am not an expert in Jave or JS, I am familiar with them.
My code
function showEmailPreview() {
// Get values from the active sheet and active row
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRowIndex();
var userEmail = sheet.getRange(row, getColIndexByName("Primary Email")).getValue();
var userFullName = sheet.getRange(row, getColIndexByName("Contact Full Name")).getValue();
var userCompanyName = sheet.getRange(row, getColIndexByName("Company Name")).getValue();
var title = sheet.getRange(row, getColIndexByName("Title")).getValue();
var company_location = sheet.getRange(row, getColIndexByName("Company Location")).getValue();
var company_phone1 = sheet.getRange(row, getColIndexByName("Company Phone 1")).getValue();
var subjectLine = "Company Proposal - " + userCompanyName;
// Create the select element
const select = `
<select id="template-select">
<option value="Proposal Template.html">Proposal Template</option>
<option value="Marketing Template.html">Marketing Template</option>
<option value="Trusted Partner Template.html">Trusted Partner Template</option>
</select>
`;
// Create the button element
const button = `<button id="send-button">Send Email</button>
<div id="preview"></div>`; //This could be a issue? The ai did not know where to place this or cut down before giving me a proper answer.
// Create an HTML output page that displays the email template, the select element, and a button to send the email
var output = HtmlService.createHtmlOutput(`
<script>
var buttonElement;
function getElementById(id) {
return document.getElementById(id);
}
function init() {
// Add a change event listener to the select element
document.getElementById('template-select').addEventListener('change', function() {
// Get the selected template file name
var templateFile = this.value;
// Read the contents of the selected file
var template = readFile(templateFile);
// Set values in the template
var html = HtmlService.createTemplate(template);
html.userFullName = userFullName;
html.userCompanyName = userCompanyName;
html.title = title;
html.company_location = company_location;
html.company_phone1 = company_phone1;
// Get the filled-in email template as a string
var emailTemplate = html.evaluate().getContent();
// Update the preview window with the selected template
document.getElementById('preview').innerHTML = emailTemplate;
});
// Add a click event listener to the button element
buttonElement = getElementById('send-button');
buttonElement.addEventListener('click', function() {
// Get the selected template file name
var templateFile = document.getElementById('template-select').value;
// Pass the selected template file name as an argument to the sendEmail function
sendEmail(templateFile);
});
}
window.onload = init;
function sendEmail(templateFile) {
// Read the contents of the selected file
var template = readFile(templateFile);
// Set values in the template
var html = HtmlService.createTemplate(template);
html.userFullName = userFullName;
html.userCompanyName = userCompanyName;
html.title = title;
html.company_location = company_location;
html.company_phone1 = company_phone1;
// Get the filled-in email template as a string
var emailTemplate = html.evaluate().getContent();
// Send the email
GmailApp.sendEmail(userEmail, subjectLine, '', {htmlBody: emailTemplate});
}
</script>
<script>
init();
</script>
${select}
${button}
`)
.setWidth(950)
.setHeight(750)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
// Display the output page in a modal dialog box
SpreadsheetApp.getUi().showModalDialog(output, 'Email Preview');
//output.evaluate();
//window.onload = init;
};
function readFile(templateFile) {
// Get the contents of the selected file
var file = DriveApp.getFilesByName(templateFile);
var contents = file.next().getBlob().getDataAsString();
return contents;
}//window.onload = init;
Results.
Here is a link for testing.
https://docs.google.com/spreadsheets/d/1gXDbtjCYfZw8kOaOMorbJ54dXyl7bh6MFM1LopTrNww/edit?usp=sharing
Its always like this when you struggle for a week and give up, And you finally post something and then you find yourself a solution. So here is the correct way of doing it.
Let's first talk about the menu. I created a file template-select-menu.gs
<form>
<label for="template">Select a template:</label><br>
<select id="template" name="template">
<option value="Proposal Template.html">Proposal Template</option>
<option value="Markting Template">Marketing Template</option>
</select>
<br><br>
<input type="button" value="Preview" onclick="google.script.run.onTemplateSelected(document.forms[0].template.value)">
</form>
then I have my preview_email.gs
function showEmailPreview() {
// Get values from the active sheet and active row
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRowIndex();
var rate = sheet.getLastRow();
var userEmail = sheet.getRange(row, getColIndexByName("Primary Email")).getValue();
var userFullName = sheet.getRange(row, getColIndexByName("Contact Full Name")).getValue();
var userCompanyName = sheet.getRange(row, getColIndexByName("Company Name")).getValue();
var subjectLine = "Company Proposal - " + userCompanyName ;
var aliases = GmailApp.getAliases()
// Create the email template selection menu
var proposalTemplate = HtmlService.createTemplateFromFile('Proposal Template.html');
var marktingTemplate = HtmlService.createTemplateFromFile('Markting Template.html');
var selectMenu = HtmlService.createTemplateFromFile('template-select-menu.html');
var selectMenuHtml = selectMenu.evaluate().getContent();
// Create an HTML output page that displays the email template selection menu and a button to send the email
var output = HtmlService.createHtmlOutput(selectMenuHtml)
.setWidth(600)
.setHeight(450);
// Display the output page in a modal dialog box
SpreadsheetApp.getUi().showModalDialog(output, 'Email Preview');
}
/**
* This function is called when the user selects a template from the drop-down menu.
* It creates an email preview using the selected template and displays it in the modal dialog box.
*/
//var html = HtmlService.createTemplateFromFile(templateFileName);
function onTemplateSelected(templateFileName) {
// Get values from the active sheet and active row
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRowIndex();
var rate = sheet.getLastRow();
var userEmail = sheet.getRange(row, getColIndexByName("Primary Email")).getValue();
var userFullName = sheet.getRange(row, getColIndexByName("Contact Full Name")).getValue();
var userCompanyName = sheet.getRange(row, getColIndexByName("Company Name")).getValue();
var subjectLine = "Company Proposal - " + userCompanyName ;
var aliases = GmailApp.getAliases();
// Create the email template and set values in the template
if (templateFileName == 'Proposal Template.html') {
var proposalTemplate = HtmlService.createTemplateFromFile('Proposal Template.html');
proposalTemplate.userFullName = userFullName;
proposalTemplate.userCompanyName = userCompanyName;
var template = proposalTemplate.evaluate().getContent();
} else if (templateFileName == 'Markting Template') {
var marktingTemplate = HtmlService.createTemplateFromFile('Markting Template.html');
marktingTemplate.userFullName = userFullName;
marktingTemplate.userCompanyName = userCompanyName;
var template = marktingTemplate.evaluate().getContent();
} else {
var template = selectMenuHtml;
}
// Create an HTML output page that displays the email template and a button to send the email
var selectMenu = HtmlService.createTemplateFromFile("template-select-menu.html");
var selectMenuHtml = selectMenu.evaluate().getContent();
var output = HtmlService.createHtmlOutput(template)
.setWidth(600)
.setHeight(450)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setContent(selectMenuHtml + '<br><br>' + template);
// Update the modal dialog box with the new email template
SpreadsheetApp.getUi().showModalDialog(output, 'Email Preview');
}
Now create the the 2 files "Proposal Template.html" and "Markting Template.html". When you switch and click preview the content will change.
Please note that I still need to update the email buttons. but this is a great start for me.

Change (or add) id name using url parameters

I need to change or create a div from an url parameters
<div class="myclass"></div>
www.example.com?change=newdiv
<div class="myclass" id="newdiv"></div>
Is it possible to do this with js?
yes you can do it like that :) :
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("change");
var element = document.getElementsByClassName("myclass");
element[0].setAttribute("id",c);
Basically you need to create new URL property using https, otherwise you will get a
TypeError: www.example.com is not a valid URL.
After that get the search parameter change and create a div where to set the id
const url = new URL('https://www.example.com?change=newdiv');
const changeParamValue = url.searchParams.get("change");
console.log("param value: " + changeParamValue)
let newDiv = document.createElement("div");
newDiv.setAttribute("id", changeParamValue);
console.log(newDiv)

How to fix Form action with method get

I have a small issues with my code.
Basically, I have a form in my index.html file:
The form from page 1 is the following:
<form method="get" name="basicSearch" id = "basicSearch" action="page2.html">
<input name="location" type="text" class="BasicSearch" id="searchInput" placeholder="Location">
<button type= "submit" class="BasicSearch" id="searchBtn" placeholder="Search"></button>
</form>
For this form, I want to use OpenWeatherMap API in order to get some weather data. My problem is the following:
I want to get what the user inputs in the form, which I think I can get by using, for example:
var searchInput = document.getElementById("searchInput");
In this variable I can store the location.
And this variable, I want to append to the link that does fetch the data from the API, in the javascript code.
When the user inputs, for example: New York, and press Search, the form action should redirect him to page2.html, where there I can show the weather data.
How can I show that weather data in the page2, with the location input from page1? I tried many times but no luck.
Some Javascript code down below:
let units = 'metric';
let searchMethod = 'q';
let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");
if (searchButton) {
searchButton.addEventListener('click', () => {
let searchTerm = searchInput.value;
if (searchTerm)
searchWeather(searchTerm);
});
}
function searchWeather(searchTerm) {
fetch(`http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`).then(result => {
return result.json();
}).then(result => {
init(result);
})
}
function init(resultFromServer){
let weatherDescriptionHeader = document.getElementById('weatherDescriptionHeader');
let temperatureElement = document.getElementById('temperature');
let humidityElement = document.getElementById('humidity');
let windSpeedElement = document.getElementById('windSpeed');
let cityHeader = document.getElementById('cityHeader');
let weatherIcon = document.getElementById('documentIconImg');
weatherIcon.src = 'http://openweathermap.org/img/w/' + resultFromServer.weather[0].icon + '.png';
let resultDescription = resultFromServer.weather[0].description;
weatherDescriptionHeader.innerText = resultDescription.charAt(0).toUpperCase() + resultDescription.slice(1);
temperatureElement.innerHTML = Math.floor(resultFromServer.main.temp) + '&#176' + " C";
windSpeedElement.innerHTML = 'Winds at ' + Math.floor(resultFromServer.wind.speed) + ' mph';
cityHeader.innerHTML = resultFromServer.name;
humidityElement.innerHTML = 'Humidity levels at ' + resultFromServer.main.humidity + '%';
}
That is some javascript code which should get the weather data.
Then, in page2, I have the following in HTML:
<div id = "weatherContainer">
<div id = "weatherDescription">
<h1 id = "cityHeader"></h1>
<div id= "weatherMain">
<div id = "temperature"></div>
<div id = "weatherDescriptionHeader"></div>
<div><img id = "documentIconImg"></div>
</div>
<hr>
<div id = "windSpeed" class = "bottom-details"></div>
<div id = "humidity" class = "bottom-details">></div>
</div>
</div>
I expected to have the weather data in page2, where the divs are.
Can somebody give me an advice, please?
Thank you!
Since the form in page1 doesn't exist in page 2, remove
let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");
if (searchButton) {
searchButton.addEventListener('click', () => {
let searchTerm = searchInput.value;
if (searchTerm)
searchWeather(searchTerm);
});
}
instead put
ley searchTerm = new URLSearchParams(location.search).get('location');
searchWeather(searchTerm);
Explanation
When the page 1 form is submitted, it will load page2 like
page2.html?location=xxxx
where xxxx is the value of the <input name='location' ...
location.search will be ?location=xxxx
URLSearchParams makes dealing with these (when you have more than one especially) easier than the old method of splitting/decoding/jumping through hoops
We can simply just submit the form and get the current form input from url on page2.html
<form method="get" name="basicSearch" id = "basicSearch" action="page2.html">
<input name="location" type="text" class="BasicSearch" id="searchInput" placeholder="Location">
<button type= "submit" class="BasicSearch" id="searchBtn" placeholder="Search">Search</button>
</form>
And on the load of page2.html (before your ajax call), we can get the 'searchInput' (location) from URL by following:
<script>
let params = (new URL(document.location)).searchParams;
var searchInput= params.get('location');
</script>
Now, we can use 'searchInput' param for your api call and fetch the result.

how to use url parameters in html? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I get URL parameters using Javascript but i can't use those variables in my html.
the JS code is this:
<script>
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("name");
console.log(c);
</script>
and my URL is localhost:8000/something?name=ABC.here i can get the value of name and show it in the browser console but when i try to set the value of an input tag in my HTML it doesn't do it and raises some errors.
my JS and html is like:
<script>
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("name");
document.getElementById("user").value =url.searchParams.get("name");
</script>
<input id="user" value"">
this should have changed the value of the input tag but doesn't.
if your #user input is call before the DOM content is loaded,
document.getElementById("user").value
javascript can't find it so he try to set "value" of an undefined element
try this :
<input id="user" value="">
<script>
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("name");
document.getElementById("user").value = c;
</script>
If you only have one URL parameter this will work. Just make sure that your input element is defined first.
A working copy JsFiddle static input
HTML
<input id="user" value="">
JS
var url = "localhost:8000/something?name=ABC" //replace with code to get url
var name = url.substring(url.indexOf("=") + 1);
document.getElementById("user").value = name;
If you need the input element to be defined after you get the URL parameter:
A working copy JsFiddle dynamic input
HTML
<div id="myDiv"> </div>
JS
var url = "localhost:8000/something?name=ABC" //replace with code to get url
var name = url.substring(url.indexOf("=") + 1);
var parent = document.getElementById("myDiv");
var input = document.createElement("input");
input.value = name;
parent.appendChild(input)

jQuery append end of url?

I have a url variable http://blah.com/blah/blah/blah and I have another url http://shop.blah.com/ I want to take the first url (blah.com) and add the ending blah/blah/blah to the second url http://shop.blah.com
So I end up with http://shop.blah.com/blah/blah/blah
Any idea of how I could do this?
var url1 = 'http://blah.com/blah/blah/blah';
var url2 = 'http://shop.blah.com/';
var newUrl = url2 + url1.replace(/^.+?\..+?\//, '');
It sounds like the jQuery-URL-Parser plugin might come in handy here:
var url = $.url(); //retrieves current url
You can also get specific parts of the URL like this:
var file = $.url.attr("file");
var path = $.url.attr("path");
var host = $.url.attr("host");
...
If you need to get Querystring parameters:
var parm = $.url.param("id");
If the intent is just to add shop to the front of the domain name:
var url2 = url1.replace('://', '://shop.');
<script>
$(document).ready(function(){
//this uses the browser to create an anchor
var blah = document.createElement("a");
//initialize the anchor (all parts of the href are now initialized)
blah.href = "http://blah.com/blah/blah/blah?moreBlah=helloWorld#hashMark";
var shop = document.createElement("a");
//initialize the anchor (all parts of the href are now initialized)
shop.href = "http://shop.blah.com/";
shop.pathname = blah.pathname; //the blahs
shop.search = blah.search; //the blah query
shop.hash = blah.hash; // the blah hashMark
alert("These are the droids you're looking for: "+shop.href);
});
</script>

Categories

Resources