Making a form in HTML where user input data and hit submit. Throws an error when the submitted.html file should load.
Cannot POST /api/submitted
The HTML on my index.html file is as follows:
<form action="/api/submitted" method="POST">
<fieldset class="fieldset">
<div>
<input type="text" name="fname" id="fname" placeholder="First Name" required><br>
<input type="text" name="lname" id="lname" placeholder="Last Name" required><br>
<input type="email" name="email" id="email" placeholder="Email" required><br>
<input type="tel" name="phone" id="phone" placeholder="Phone #" required><br>
</div>
<div>
In which campus are you interested?<br>
<select name="campus" id="" required>
<!-- options -->
<option value="">--Select--</option>
<option value="Towson">Towson</option>
<option value="Dundalk">Dundalk</option>
<option value="ChevyChase">Chevy Chase</option>
<option value="SilverSpring">Silver Spring</option>
</select><br>
</div>
<div>
About which workshop would you like to learn more?<br>
<input type="text" name="request" id="request"><br>
</div>
<div>
By submitting your information below, you agree to our
Terms of Use
and
Privacy Policy<br>
</div>
<div>
<button type="submit">Submit</button>
</div>
</fieldset>
</form>
And then my submitted.html text is:
<!DOCTYPE html>
<html lang="en">
<style type="text/css">#import url("css/submitted.css");</style>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Submitted Form</title>
</head>
<body>
<header>
Thank you for your interest in our workshops! A member of our team will reach out soon!
</header><br><br>
<p>
Exit<br><br>
Return to form.
</p>
</body>
</html>
The JavaScript is as follows:
app.post('/api/submitted', async (req, res) => {
console.log('You posted from a form!');
console.log(req.body);
const data = { ...req.body, dateOfApplication: new Date() }; // ... copies whatever i have in an array and makes a deep copy
const collection = client.db("applications").collection("applicants");
try {
await collection.insertOne(data);
} catch (error) {
console.log(error.message);
}
res.status(201);
res.redirect('/submitted.html');
});
I am trying to get the input data stored onto a MongoDB server, and then that data can be viewed on a separate HTML file. Of course, the data is not being stored, too.
try to change form action to full end point api to be like this
http://localhost/api/submitted
the action you entered is a relative path the will redirect to
your_index_directory/api/submitted
try to use absolute path of full url as i mentioned before
Related
I am getting an error when trying to check if an input field is empty or not. I tried the function with First Name input Field but not working.
I am trying to check if the First Name input field is empty the input border should turn red if not the border should stay the same.
HERE IS MY CODE
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Exercise 2</title>
<script type="text/javascript">
function validateField(fieldID){
check = document.getElementById("fieldID");
if(check.value.length == 0){
check.style.borderColor ="red";
}
}
</script>
</head>
<body>
<h1>Flight Reservation</h1>
<form method="POST" action="">
<label for="userFirstName">First Name:</label><br>
<input type="text" name="userName" id="userFirstName" onblur="validateField(userFirstName);">
<br>
<label for="userLastName">Last Name:</label><br>
<input type="text" name="userLast"id="userLastName">
<br>
<label>class:</label>
<label for="businessRadio">Business</label>
<input type="radio" name="ticketType" id="businessRadio">
<label for="economyRadio">Economy</label>
<input type="radio" name="ticketType" id="economyRadio">
<br>
<label for="wheelchair">Wheelchair</label>
<input type="checkbox" name="wheelchair" id="wheelchair">
<br>
<label for="passengers">Passengers:</label>
<input type="number" name="passengers" id="Passengers">
<br>
<input type="submit" name="Send" >
<input type="reset" name="Cancel">
</form>
</body>
</html>
You are passing fieldId and then trying to access with "" which actually converts the fieldId to a string. I have fixed the issue, please check the code below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Exercise 2</title>
<script type="text/javascript">
function validateField(fieldID){
check = document.getElementById(fieldID);
if(check.value.length == 0){
check.style.borderColor ="red";
}
}
</script>
</head>
<body>
<h1>Flight Reservation</h1>
<form method="POST" action="">
<label for="userFirstName">First Name:</label><br>
<input type="text" name="userName" id="userFirstName" onblur="validateField('userFirstName');">
<br>
<label for="userLastName">Last Name:</label><br>
<input type="text" name="userLast"id="userLastName">
<br>
<label>class:</label>
<label for="businessRadio">Business</label>
<input type="radio" name="ticketType" id="businessRadio">
<label for="economyRadio">Economy</label>
<input type="radio" name="ticketType" id="economyRadio">
<br>
<label for="wheelchair">Wheelchair</label>
<input type="checkbox" name="wheelchair" id="wheelchair">
<br>
<label for="passengers">Passengers:</label>
<input type="number" name="passengers" id="Passengers">
<br>
<input type="submit" name="Send" >
<input type="reset" name="Cancel">
</form>
</body>
</html>
The error occurs when you are trying to get check.value.length when check === null. So this sentences it's returning null value:
check = document.getElementById("fieldID");
Try to change that line to:
check = document.getElementById(fieldID);
Because you are writting a literal string, not using the variable.
There are two problems with the above code:
1: change below line of code
check = document.getElementById("fieldID");
to
check = document.getElementById(fieldID);
2: use string literals to pass id of the field to funtion called onblur
onblur="validateField(userFirstName);"
replace above line with
onblur="validateField('userFirstName');"
This question already has answers here:
For loop for HTMLCollection elements
(13 answers)
Closed 8 months ago.
I have a small menu of 5 items here. What I am trying to do is if the "lollipops" option is selected and a user clicks add to cart button, JavaScript should create a new tag. I am new to JavaScript and would appreciate any directions or suggestions about what I am doing wrong. I posted a copy of my HTML and JavaScript code below, so please take a look thanks.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Assignment 2</title>
</head>
<body>
<form>
<div class="container">
<div class="material">
<label for="items">Choose an Item: </label>
<select id="items">
<option id="lollipops">Box of Lollipops - $2.00</option>
<option id="recipes">Book of Recipes - $4.99</option>
<option id="giftwrap">Gift wrapper - $2.75</option>
<option id="dogTreats">Dog Treats - $5.00</option>
<option id="catTreats">Cat Treats - $$5.00</option>
</select>
<input type="button" value="Add To Cart" id="addToCart" onclick="addToCart()">
<div id="cart">
<p id="beforeTax">Before Tax: </p>
<p id="price">Total: </p>
</div>
<br>
<label for="name">Name: </label>
<input type="text" id="name" placeholder="Enter name">
<label for="email">Email: </label>
<input type="email" id="email" placeholder="Enter email">
<br><br><br>
<label for="creditCard">Credit card number</label>
<input type="text" id="creditCard" placeholder="xxxx-xxxx-xxxx-xxxx">
<label for="expiryDate">Expiry Date: </label>
<input type="month">
<br><br><br>
</div>
</div>
<input type="button" id="submit" value="Submit">
</form>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
JavaScript
//let lollipopsPrice = document.getElementById("lollipops").value;
//let recipePrice= document.getElementById("recipes").value;
//let giftwrapPrice = document.getElementById("giftwrap").value;
//let dogTreatsPrice = document.getElementById("dogsTreats").value;
//let catTreatsPrice = document.getElementById("catTreats").value;
function addToCart()
{
let item=document.getElementsByTagName("option").value;
if (item.value=="Box of Lollipops - $2.00")
{
document.write("<p>Box of Lollipops - $2.00</p>");
}
console.log();
}
To write something in the document you can use can use append, or innerHTML.
When the option is selected it will fire the addToCart function, and depending on where you want to write the new element (when you say "javascript should create a new tag", I imagine you mean a new element).
As you can see following the links, you create a div,p and text inside the p, like this:
let div = document.createElement("div");
let p = document.createElement("p");
div.append(p)
p.append("some text")
or you could use innerHTML like this:
p.innerHTML = "some text in innerHTML"
Even though, as stated on the Developer Mozilla site, innerHTML presents some vulnerability issues and it is recommended to use the setHTML() method to sanitize user inputs. In your case it's a selection so it is not much relevant.
I'm trying to create a user input where the user can choose a stock Symbol, a Start Date, End Date and Interval. I would then like for this information to be passed along the javascript function api to retrieve information about that specific stock such as open, high, low, close, etc. The javascript function is working when I call the api function, but I'm not sure if I'm using the right code on HTML to use the user input and then passing this input onto the api() function on javascript once the user presses the "Execute" button
Javascript:
import yahooFinance from 'yahoo-finance2';
let symbolNew = document.getElementById("symbol").value;
let periodStart = document.getElementById("period1").value;
let periodEnd = document.getElementById("period2").value;
let intervalNew = document.getElementById("interval").value;
async function api(symbol, start, end, val) {
const query = String(symbol);
const queryOptions = { period1: new Date(start), period2: new Date(end), interval: String(val) };
let result = await yahooFinance.historical(query, queryOptions);
let resultWithSymbol = result.map((item) => ({ ...item, symbol: query })); //... is called the spread operator - it concatonates things
console.log(resultWithSymbol);
return resultWithSymbol;
};
api(symbolNew, periodStart, periodEnd, intervalNew);
HTML:
<!DOCTYPE html><p>API</p>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="module" src="../dist/bundle.js"></script>
<title>Document</title>
</head>
<body>
<div class="symbol">
<p id="symbol"></p>
<label for="name">Symbol (4 characters):</label>
<input type="text" id="symbol" name="symbol" required
minlength="4" maxlength="4" size="10" placeholder="Exemplo: TSLA">
</div>
<div class="interval">
<label for="name">Interval: (1d, 1wk or 1mo):</label>
<input type="text" id="interval" name="interval" required
minlength="2" maxlength="3" size="10" placeholder="Exemplo: 1d">
</div>
<div class="period1">
<label for="name">Start Date:</label>
<input type="text" id="period1" name="period1" required
minlength="10" maxlength="10" size="20" placeholder="Exemplo: 2021-08-20">
</div>
<div class="period2">
<label for="name">End Date:</label>
<input type="text" id="period2" name="period2" required
minlength="10" maxlength="10" size="20" placeholder="Exemplo: 2021-08-25">
</div>
<div class="button">
<input type="button" name="buttonExecute" value="Execute" onclick="api(document.getElementById('symbol'),document.getElementById('period1'),document.getElementById('period2'),document.getElementById('interval'))"></input>
</div>
</body>
</html>
I'm aware that Node js doesn't recogniz "document." so I'll be using Webpack or Bable to get the input of the api() function onto the HTML
Thank you in advance
'value' (document.getElementById('symbol').value;) is missing in the HTML onclick event.
I am trying to create a simple form using Javascript, but I am facing an issue while trying to display somethings on the console. The issue here is that whenever I click on the submit button, Nothing is displayed on the console despite giving the command e.preventdefault(). At present I want the text Hello to be displayed on console when it satisfies the condition, but even though the condition is satisfied, nothing is displayed.
Herewith attaching the Javascript and HTML code for the same
const passlength = 10;
const firstname = document.getElementById("firstname");
const lastname = document.getElementById("lastname");
const emailid = document.getElementById("emailid");
const password = document.getElementById("pass");
const confirmpassword = document.getElementById("passconfirm");
const phonenumber = document.getElementById("phno");
const form = document.querySelector(".mainform");
function testfunc() {
console.log(type(emailid));
}
function checkpass(pass) {
if (pass>=passlength) {
console.log("Hello");
}
else{
console.log("Out");
}
}
form.addEventListener('submit',function(e){
e.preventDefault();
checkpass(password);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register with us</title>
</head>
<body>
<div class="mainform">
<form>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname"><br>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname"><br>
<label for="emailid">Email ID:</label>
<input type="email" id="emailid" name="emailid"><br>
<label for="pass">Enter password:</label>
<input type="password" id="pass" name="pass"> <br>
<label for="passconfirm">Confirm password:</label>
<input type="password" id="passconfirm" name="passconfirm"> <br>
<label for="phno">Phone number:</label>
<input type="number" id="phno" name="phno">
<br> <br>
<input type="submit" value="Submit" id="submit">
</form>
</div>
</body>
</html>
The problem is in your If statement. You are comparing a number with an HTML element. You still need these two.
.value returns the value of the html element
https://www.w3schools.com/jsref/prop_text_value.asp
.length returns the length of a string
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/length
This is how you compare two numbers, as you intended.
So your new IF condition must be:
(pass.value.length>=passlength)
I've written a validator for my HTML although I'm not sure where I'm going wrong.
What I'm trying to do below is determine if there is any text in the "First Name" box altogether. There is underlying css to the code but I believe my issue is surrounding my onsubmit and validate function as nothing in the javascript seems to be running once I click the submit button.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<link rel="stylesheet" type="text/css" href="NewPatient.css">
<script>
function validate() {
var invalid = false;
if(!document.Firstname.value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
Looks like the culprit was your attempt to access Firstname on the document object.
I replaced it with the more standard document.getElementById() method and its working.
Some reading on this: Do DOM tree elements with ids become global variables?
function validate() {
var invalid = false;
if(!document.getElementById('Firstname').value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false;
}
return true;
}
#form-error {
display: none;
}
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate()">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
There are a couple of typos, and I'll suggest something else as well. First, a fix or three in the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<script>
function validate() {
const invalid = document.getElementById("Firstname").value.length == 0;
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
My suggestion is that you also look into built-in HTML form validation attributes. I'm thinking you're reinventing the wheel for things like requiring a non-empty Firstname. Why not this instead of JavaScript?
<input type="text" name="Firstname" id="Firstname" placeholder="First Name" required />
And many others, like minlength="", min="", step="", etc.
Plus there's still a JavaScript hook into the validation system with .checkValidity() so you can let the built-in validation do the heavy lifting, and then throw in more of your own custom aspects too.