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)
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');"
I have a very simple form here with 2 required inputs.
When you click submit button without filling them - there are popups saying that you should do it. The problem is that popups are showed one by one - for example, if both inputs arent filled, only the first input will have this popup. And when the first one is filled only then it goes to the second and vice versa.
Is there any way to show all the fields that are not filled/filled incorrect during the validation at the same moment? So the user sees immediately everything he/she has to fill?
I am quite new to this, so please help me find the solution in pure JS (if it is about JS).
Here is the code:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST">
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" required=""
oninvalid="setCustomValidity('Enter first name')" oninput="setCustomValidity('')"
placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" required=""
oninvalid="setCustomValidity('Enter last name')" oninput="setCustomValidity('')"
placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
The code you provided is using a built in function of JavaScript, setCustomValidity(). This most likely is the reason for the pop-up. Instead we can write a custom function to show a little paragraph/span with the text instead.
Here we have a HTML form, but with a call for the custom function validateFields(), when clicking the Submit button:
<form class="" action="your-post-page.html" method="post" id="my-form-id" name="my-form-name" onsubmit="return validateFields()" target="_blank" class="validate" novalidate="">
<input id="name_1" type="text">
<br><br>
<input id="name_2" type="text">
<br><br>
<input id="name_3" type="text">
<br><br>
<input type="submit" name="" value="SUBMIT FORM">
</form>
<p id="error_messages" style="background-color: red; color: white;"></p>
The JS that makes it happen:
(custom function that reacts to inputs being empty and lets the user know which fields need fixing, put code before the </html> tag in your html-page)
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["name_1", "name_2", "name_3"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["Name 1", "Name 2", "Name 3"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["my-form-id"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
Now lastly, here is your own code with this example:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST" onsubmit="return validateFields()" >
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
<!-- here I added a new box for the error messages in your code -->
<div class="">
<p id="error_messages" style="background-color: red; color: white;"></p>
</div>
</div>
</form>
</body>
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["first_name", "lastName"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["First name", "Last name"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["mainForm"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
</html>
That was with custom scripting to get a box that you can style and enhance yourself, in this case below the form. But if you are okay with some default (and perhaps not unified styling, due to browser differences) you can also just remove the JavaScript function you had in your original code, the setCustomValidity(''). That will leave you with a generic message using the already present attribute required="", which produces this:
To achive that behaviour, change your tags for each field to look like this instead:
<input id="first_name" name="first_name" type="text" value="" required="" placeholder="Enter first name">
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 new to HTML and JavaScript. I just made a simple page to add two numbers. The output that I am getting is correct but when I click the sum button the sum is there for a fraction of second and then again the page reloads itself.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First</title>
<script>
function get_sum() {
let num_a = parseInt(document.getElementById('first').value);
let num_b = parseInt(document.getElementById('second').value);
document.getElementById('sum').innerText = (num_a + num_b).toString(10);
}
</script>
</head>
<body>
<form id="form" onsubmit="return get_sum()">
<label>First Number: <input type="text" id="first" placeholder="Enter a number" required></label>
<br>
<label>Second Number: <input type="text" id="second" placeholder="Enter a number" required></label>
<button type="submit">Sum </button>
</form>
<h1 id="sum"></h1>
</body>
</html>
You need to pass the event and add event.preventDefault(); at the beginning of the function to prevent page from reloading since it's a submit button:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First</title>
<script>
function get_sum(event) {
event.preventDefault();
let num_a = parseInt(document.getElementById('first').value);
let num_b = parseInt(document.getElementById('second').value);
document.getElementById('sum').innerText = (num_a + num_b).toString(10);
}
</script>
</head>
<body>
<form id="form" onsubmit="return get_sum(event)">
<label>First Number: <input type="text" id="first" placeholder="Enter a number" required></label>
<br>
<label>Second Number: <input type="text" id="second" placeholder="Enter a number" required></label>
<button type="submit">Sum </button>
</form>
<h1 id="sum"></h1>
</body>
</html>
The onsubmit must return false to prevent browser from submitting it to server.
Like this
<form id="form" onsubmit="get_sum(); return false;">
You can add an event listener to handle the click after you change the type to "button". Or you can stop the event from propagating to the actual "submit" action. OR, do both to prevent the submit of the form.
Why both? A form can also be submitted by hitting "return/enter" or via script.
This is perhaps a bit of overkill but shows how to handle the events.
function get_sum(event) {
event.preventDefault();
let num_a = parseInt(document.getElementById('first').value);
let num_b = parseInt(document.getElementById('second').value);
document.getElementById('sum').innerText = (num_a + num_b).toString(10);
}
const sumButton = document.getElementById('sum-click');
sumButton.addEventListener("click", get_sum, false);
const form = document.getElementById('form');
form.addEventListener('submit', get_sum);
<form id="form">
<label>First Number: <input type="text" id="first" placeholder="Enter a number" required></label>
<br>
<label>Second Number: <input type="text" id="second" placeholder="Enter a number" required></label>
<button id="sum-values" type="submit">Sum </button>
<button id="sum-click" type="button">Sum (Not submit)</button>
</form>
<h1 id="sum"></h1>
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.