I am new to HTML and css and this is my first html code after a decade, I am trying to create a simple form with 2 basic requirement. I have a search field which runs a script which does a rest call with the value inserted in text box and return list of values(1 - 10). I want to show those values under my search box and also assign it to a variable and fetch it when submit is hit so that I can pass it to another rest call. For the below code, I commended out the rest call in script and added and dummy value. My end objective is to get all the values in the form, including the one returned from search and make a http call on submit button. How can I achieve this? I never did a frontend/html development so any references would be helpful.
<!DOCTYPE html>
<html style="font-size: 16px;" lang="en"><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<meta name="keywords" content=" Simplified UI">
<meta name="description" content="">
<title>Home</title>
<link rel="stylesheet" href="nicepage.css" media="screen">
<link rel="stylesheet" href="Home.css" media="screen">
<script class="u-script" type="text/javascript" src="jquery.js" defer=""></script>
<script class="u-script" type="text/javascript" src="nicepage.js" defer=""></script>
<meta name="generator" content="Nicepage 4.13.4, nicepage.com">
<link id="u-theme-google-font" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i|Open+Sans:300,300i,400,400i,500,500i,600,600i,700,700i,800,800i">
<script>
// define the callAPI function that takes a first name and last name as parameters
var callAPI = (title_name)=>{
// instantiate a headers object
var myHeaders = new Headers();
// add content type header to object
myHeaders.append("Content-Type", "application/json");
// using built in JSON utility package turn object to string and store in a variable
var raw = JSON.stringify({"title_name":title_name});
// create a JSON object with parameters for API call and store in a variable
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
// make API call with parameters and use promises to get response
<!-- fetch("API-INVOKE-URL", requestOptions)-->
<!-- .then(response => response.text())-->
<!-- .then(result => alert(JSON.parse(result).body))-->
<!-- .catch(error => console.log('error', error));-->
{"123456", "bob"}
}
</script>
<meta name="theme-color" content="#478ac9">
<meta property="og:title" content="Home">
<meta property="og:type" content="website">
</head>
<body data-home-page="Home.html" data-home-page-title="Home" class="u-body u-xl-mode"><header class=" u-clearfix u-header u-section-row-container" id="sec-70ca"><div class="u-section-rows">
<div class="u-clearfix u-section-row u-white u-section-row-1" data-animation-name="" data-animation-duration="0" data-animation-delay="0" data-animation-direction="">
<div class="u-clearfix u-sheet u-valign-top u-sheet-1">
<h2 class="u-text u-text-default u-text-1">Simplified UI</h2>
<div class="u-form u-form-1">
<form action="#" method="POST" class="u-clearfix u-form-spacing-5 u-form-vertical u-inner-form" name="form" style="padding: 23px;">
<div class="u-form-group u-form-name">
<label for="name-4c18" class="u-label">name</label>
<input type="text" placeholder="ML Audience name" id="name-4c18" name="Name" class="u-border-2 u-border-palette-4-light-3 u-input u-input-rectangle u-palette-4-light-3 u-radius-10" required="">
</div>
<div class="u-form-group">
<label for="email-4c18" class="u-label">Id</label>
<input type="text" placeholder="Enter email id" id="email-4c18" name="emailId" class="u-border-2 u-border-palette-4-light-3 u-input u-input-rectangle u-palette-4-light-3 u-radius-10" required="required">
</div>
<div class="u-form-group u-form-select u-form-group-3">
<label for="select-dc18" class="u-label">Country</label>
<div class="u-form-select-wrapper">
<select id="select-dc18" name="Country" class="u-border-2 u-border-palette-4-light-3 u-input u-input-rectangle u-palette-4-light-3 u-radius-10" required="required">
<option value="US">US</option>
<option value="PL">PL</option>
<option value="IN">IN</option>
<option value="KOR">KOR</option>
<option value="CH">CH</option>
</select>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" version="1" class="u-caret"><path fill="currentColor" d="M4 8L0 4h8z"></path></svg>
</div>
</div>
<div class="u-form-group u-form-select u-form-group-4">
<label for="select-c14d" class="u-label">Are you a first time visitor</label>
<div class="u-form-select-wrapper">
<select id="select-c14d" name="NewShowOrNot" class="u-border-2 u-border-palette-4-light-3 u-input u-input-rectangle u-palette-4-light-3 u-radius-10" required="required">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" version="1" class="u-caret"><path fill="currentColor" d="M4 8L0 4h8z"></path></svg>
</div>
</div>
<div class="u-form-group u-form-group-5">
<label for="text-049f" class="u-label"> Title</label>
<input type="text" id="text-049f" name="ProgramTitle" class="u-border-2 u-border-palette-4-light-3 u-input u-input-rectangle u-palette-4-light-3 u-radius-10">
<button type="button" onclick="callAPI(document.getElementsByName('ProgramTitle')[0].value)">search</button>
</div>
<div class="u-align-center u-form-group u-form-submit">
Submit your request
<input type="submit" value="submit" class="u-form-control-hidden">
</div>
<div class="u-form-send-message u-form-send-success"> Thank you! Your request has been sent. </div>
<div class="u-form-send-error u-form-send-message"> Unable to send your request. Please fix errors then try again. </div>
</form>
</div>
</div>
</div>
<div class="u-section-row u-section-row-2">
<div class="u-clearfix u-sheet u-sheet-2"></div>
</div>
</div></header>
<footer class="u-align-center u-clearfix u-footer u-grey-80 u-footer" id="sec-0cc5"><div class="u-clearfix u-sheet u-sheet-1">
<p class="u-small-text u-text u-text-variant u-text-1">Sample text. Click to select the Text Element.</p>
</div></footer>
</body></html>
The question wasn't perfectly clear in some details..
Anyway I simplified your html a bit to make the solution more clear.
Then I focused on your logic to fetch results from your api on the click event of the search button, so that after the call returns, its result gets echoed in a dedicated html target (whose id is api_results located right under the search button).
I was confused on how that array was supposed to be, because in your question you say values from 1-10, while in your code you put a dummy array like ["123456", "bob"]. Since it was not relevant to the focus of the question, I left it as written on your code.
Such results array gets also saved as a JSON string in a dedicated new hidden input field (id: apiresults) that will be sent with the rest of the data when the form is submitted.
Plus, there's a listener for the submit event of the form that will be called on submit (if input data passed validation) and will fetch that array from the hidden field so that if you want to call a further api, you have that data.
This is the demo:
//on document ready
document.addEventListener('DOMContentLoaded',()=>{
//add click event listener to search button
document.getElementById('search').addEventListener('click', (event)=>{
//fetch the title_name
const title_name = document.getElementsByName('ProgramTitle')[0].value;
//call the api
const results = callAPI(title_name);
//get the html element to show output
const outputTarget = document.querySelector('.api_results');
//reset its inner content
outputTarget.innerHTML = "";
//loop through each result item
results.forEach((o,i)=>{
//create a list item element and append it to the output
const p = document.createElement('li');
p.textContent = o;
outputTarget.appendChild(p);
});
//saves the api results as a json string in the hidden input field (id=apiresults)
document.getElementById('apiresults').value = JSON.stringify(results);
});
//add submit event listener to form
document.getElementById('form').addEventListener('submit', (event)=>{
//here you have the array returned from the search api call
const encoded = document.getElementById('apiresults').value;
const decoded = JSON.parse( encoded );
//here you are supposed to call your next api with that data?
//this preventDefault is meant to stop the real submit because here it would break
//just uncomment this in your real production code
event.preventDefault();
console.log(`form submitted - array data from api was (as json): ${encoded}`);
});
});
// define the callAPI function that takes a first name and last name as parameters
const callAPI = (title_name)=>{
// instantiate a headers object
const myHeaders = new Headers();
// add content type header to object
myHeaders.append("Content-Type", "application/json");
// using built in JSON utility package turn object to string and store in a variable
const raw = JSON.stringify({"title_name":title_name});
// create a JSON object with parameters for API call and store in a variable
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
// make API call with parameters and use promises to get response
/*
fetch("API-INVOKE-URL", requestOptions)
.then(response => response.text())
.then(result => alert(JSON.parse(result).body))
.catch(error => console.log('error', error));
*/
return ["123456", "bob"];
}
html{
font-size: 16px;
}
form{
padding: 23px;
}
.formgroup{
display: flex;
margin-bottom: 1rem;
}
.formgroup label{
width: 20%;
}
.api_results{
border: dashed 3px gray;
margin: 1rem 0 1rem 0;
padding: 1rem;
}
button, input[type=submit]{
padding: 0.25rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Simplified Form</h1>
<form action="#" method="POST" name="form" id="form">
<div class="formgroup">
<label for="name-4c18">name</label>
<input
id="name-4c18" name="Name"
type="text"
placeholder="ML Audience name"
required="">
</div>
<div class="formgroup">
<label for="email-4c18">Id</label>
<input
id="email-4c18" name="emailId"
type="text"
placeholder="Enter email id"
required="required">
</div>
<div class="formgroup">
<label for="select-dc18">Country</label>
<div>
<select
id="select-dc18" name="Country"
required="required">
<option value="US">US</option>
<option value="PL">PL</option>
<option value="IN">IN</option>
<option value="KOR">KOR</option>
<option value="CH">CH</option>
</select>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14" height="12" version="1">
<path fill="currentColor" d="M4 8L0 4h8z"></path>
</svg>
</div>
</div>
<div class="formgroup">
<label for="select-c14d">Are you a first time visitor</label>
<div>
<select
id="select-c14d" name="NewShowOrNot"
required="required">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14" height="12" version="1">
<path fill="currentColor" d="M4 8L0 4h8z"></path>
</svg>
</div>
</div>
<div class="formgroup">
<label for="text-049f">Title</label>
<input id="text-049f" name="ProgramTitle" type="text">
<button
id="search"
type="button"
onclick="callAPI()">
search
</button>
</div>
<div class="api_results">
</div>
<input type="hidden" id="apiresults" name="apiresults" value="">
<div class="formgroup">
<input type="submit" value="submit">
</div>
</form>
Here is the JavaScript:
myform.addEventListener('submit', (event) => {
fetch("url", {mode: "no-cors"})
.then(res=> {
if(res.ok){
console.log("cats")
}
else{
event.preventDefault()
document.getElementById("subcim_error_message").innerHTML="You must add a title!"
return false
}
})})
Here is the html:
<head>
<title>pH Login</title>
<link rel="stylesheet" href="../styles/ph-styles.css"/>
</head>
<body>
<header>
<h1>parry Hotter School for Alchemy and Pyromancy</h1>
</header>
<div id="hat" style="display: flex; justify-content: center;">
<img src="https://www.renderhub.com/realityscanning/old-boot-with-plants-inside/old-boot-with-plants-inside-01.jpg" style="height: 15rem" alt="Sorting Boot"/>
</div>
<span class="error_form" id="subcim_error_message"></span>
<form name="myform">
<section class="two_columns">
<label for="username">Username:</label>
<input id="username" placeholder="parry Hotter" type="text"/>
<label for="password">Password:</label>
<input id="password" placeholder="*******" type="password" maxlength="20"/>
</section>
<input type="submit"/>
</form>
<footer>
<h6>©Copyright pHSfAaP. All rights reserved.</h6>
</footer>
<style>
#hat{
margin: 3em;
}
img{
border: 1em;
border-style: solid;
border-color: steelblue;
}
</style>
<script src="../scripts/parry-hotter-login.js"></script>
</body>
I am trying to display an error message when someone enters invalid credentials but everytime it happens the page refreshes so the error message immediately vanishes
Literally by adding client site validation. As per the MDN:
Before submitting data to the server, it is important to ensure all required form controls are filled out, in the correct format. This is called client-side form validation, and helps ensure data submitted matches the requirements set forth in the various form controls. This article leads you through basic concepts and examples of client-side form validation.
Then there's server side validation of course. For that you could setup focus or keypress event handlers to validate input and add some UI hints, e.g., messages, colors, checkmarks, and toggle the submit button state.
UPDATE
Here's a snippet that adds the required attribute to the inputs (client-side validation) and a handler for the submit event (server-side validation). The trick to cancelling submission of a form is for the onsubmit handler to return false.
document.getElementById('myform').onsubmit = function()
{
// mock response
res = { status: "failed", reason: "the user name does not exist." };
if (res.status !== "ok")
{
alert(res.reason);
return false;
}
return true;
}
<head>
<title>pH Login</title>
<link rel="stylesheet" href="../styles/ph-styles.css"/>
</head>
<body>
<header>
<h1>parry Hotter School for Alchemy and Pyromancy</h1>
</header>
<div id="hat" style="display: flex; justify-content: center;">
<img src="https://www.renderhub.com/realityscanning/old-boot-with-plants-inside/old-boot-with-plants-inside-01.jpg" style="height: 15rem" alt="Sorting Boot"/>
</div>
<span class="error_form" id="subcim_error_message"></span>
<form id="myform">
<section class="two_columns">
<label for="username">Username:</label>
<input id="username" placeholder="parry Hotter" type="text" required/>
<label for="password">Password:</label>
<input id="password" placeholder="*******" type="password" maxlength="20" required/>
</section>
<input type="submit"/>
</form>
<footer>
<h6>©Copyright pHSfAaP. All rights reserved.</h6>
</footer>
<style>
#hat{
margin: 3em;
}
img{
border: 1em;
border-style: solid;
border-color: steelblue;
}
</style>
<script src="../scripts/parry-hotter-login.js"></script>
</body>
While this code does work, I want to be able to transfer the code to a different html page when the user clicks submit after filling out the form.
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<STYLE>
body {
background-color: #2C2F33
}
.form {
font-family: Arial;
color: #FFFFFF
}
.
</STYLE>
<SCRIPT>
function testResults (form) {
var Name = form.Name.value;
var Bio = form.Bio.value;
document.write (Name);
document.write("<br>");
document.write (Bio);
}
</SCRIPT>
</HEAD>
<BODY>
<DIV CLASS="FORM">
<FORM NAME="myform" ACTION="" METHOD="GET" >What is your name? This can be your first name, or an alias your known by. <BR>
<INPUT TYPE="text" NAME="Name" VALUE="" STYLE="height: 50px; width: 400px;"><P>
<FORM NAME="myform" ACTION="" METHOD="GET">Who are you? What do you do? <BR>
<INPUT TYPE="text" NAME="Bio" VALUE="" STYLE="height: 200px; width: 400px;"><P>
<div class="">
<INPUT TYPE="button" NAME="button" Value="Submit" onClick="testResults(this.form)">
</div>
</FORM>
</DIV>
</BODY>
</HTML>
Can anyone please tell me how to achieve this? I've tried making another html page then writing the info, but it doesn't work.
Side note, yes there is some code that isn't filled out
The action property specifies which page it is sent to. Right now it is blank and won't send to another page, even if all the other mark-up was correct.
There are many ways to achieve what you are trying to do. This is only one aspect to consider initiallly.
I'm new to coding and I wanted to make data entry more uniform in my worplace. And so I have been trying to create a html form in a sidebar and submit the resulting data to a speadsheet.
I have my form and my sidebar working but no matter what I try or which tutorial I follow I can't seem to wrap my head around how to get the data from the html form to my spreadsheet.
Here is the .gs
function onOpen(){
SpreadsheetApp.getUi()
.createMenu('Menu CFC')
.addItem('Ajout','showSidebar')
.addToUi();
showSidebar();
}
function showSidebar(){
var html = HtmlService.createHtmlOutputFromFile('menuCFC')
.setTitle('Mon menu CFC')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
function formCFCSubmit(form_data){
var sheet = spreadsheetApp.getActive().getSheetByName('Feuille 1');
sheet.([form_data.nom,form_data.numéro])
}
and here is a simplified version of my html form for testing purpose.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form name="formAjoutCFC">
<div class ="block form-group">
<label for="Nom">Nom</label>
<input type="text" name="nom" id="nom" placeholder="Nom" required>
</div>
<div class ="block form-group">
<label for="Numéro">Numéro</label>
<input type="text" name="numéro" id="numéro" placeholder="Numéro" required>
</div>
<div class="block">
<button type="submit" class="action">Valider</button>
</div>
<div calss="block">
<input type="reset">
</div>
</form>
<script>
document.querySelector("#formAjoutCFC").addEventListener("submit", //not sure about the #
function(e)
{
e.preventDefault();
google.script.run.formCFCSubmit(this);
);
</script>
</body>
</html>
Any help would be welcome as I'm out of my depth at the moment ^^
You are doing all right #Lugh, very close to your goal indeed. But you need to take care of some things:
Your showSideBar function is alright too.
On your formCFCSubmit(form_data) you have errors:
The class you want to call from is SpreadsheetApp not (s)preadsheetApp.
sheet.([form_data.nom,form_data.numéro]) is not an existing method.
// For testing purposes, you can paste the data in ranges "A1" and "B1" for example:
function formCFCSubmit(form_data){
var sheet = SpreadsheetApp.getActive().getSheetByName('Feuille 1');
sheet.getRange('A1').setValue(form_data.nom);
sheet.getRange('B1').setValue(form_data.numero);
// Notice accent removed from numero!
// Putting accents in code will give you headaches sooner than later...
}
On your menuCFC.html:
Here is where most of your trouble is coming from...
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<!-- Notice 'id'! That's what the # in the query selector is referencing. Not name -->
<form id="formAjoutCFC">
<div class="block form-group">
<label for="Nom">Nom</label>
<input type="text" name="nom" id="nom" placeholder="Nom" required>
</div>
<div class="block form-group">
<label for="Numero">Numéro</label>
<input type="text" name="numero" id="numero" placeholder="Numéro" required>
</div>
<div class="block">
<button type="submit" class="action">Valider</button>
</div>
<div class="block">
<input type="reset">
</div>
</form>
<script>
document.querySelector("#formAjoutCFC")
.addEventListener(
"submit",
function(e) {
e.preventDefault();
google.script.run.formCFCSubmit(this);
}
);
</script>
</body>
</html>
Now the script in your sidebar, can get the form by id, and when submitted execute the formCFCSubmit function that does what you want it to with form_data.
Keep on coding!
Notes:
You should read official documentation now that you are into coding.
Read about the SpreadsheetsApp class from Apps Script's Spreadsheet service to find out which functions you can use to tailor to your need.
[edited] I'm trying to include an email signup box on my website with Parse on the backend.
Problem: The email ids entered aren't getting saved into the Parse database.
here's the HTML with corresponding JS. I'm still learning JS so I might have picked up some code from here and there.
<form id="signup-form" class="align-center">
<div class="form-group align-center" style="width: 90%;">
<input type="text" class="form-control" name="email" id="email" placeholder="get informed when it's online!" style="font-size: 1em; width: 100%; float: left;"/>
<button id="signup-button" class="btn btn-default" style="margin-top: 10px;" >count me in!</button>
</div>
</form>
Javascript:
$(document).ready(function() {
$("#signup-button").click(function() {
Parse.$ = jQuery;
Parse.initialize("n7cfi9v9FErlM13bSC4qb6obHr0c9lSNmEgyBGTB", "NHA6CciUx6xXCvrQwHGTG48D7ggItvUlrYE36mTT");
var SignupList = Parse.Object.extend("signup_list");
var signup = new SignupList();
signup.save({email: $('#email').val()}).then(function(object) {
alert($('#email' + " enrolled in list!").val());
});
});
});
Don't know what I'm doing wrong. Help.