How do I prevent my page from refreshing on submit - javascript

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>

Related

How to put user data on a different page

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.

How to make angularjs log default html5 validation messages when an input field is invalid?

So, I have been working on a project where I use angularjs to validate form input fields. The thing is, I want angularjs log the default html5 validation messages like 'Please Fill out this field' when the input
fields are empty. It should be something similar to the code below:
var x = document.getElementById("myForm");
var y = document.getElementById("email");
var z = document.getElementById("error");
x.addEventListener("submit", (e) => {
if (y.checkValidity() === false) {
e.preventDefault();
z.innerHTML = y.validationMessage;
}
});
body {
background-color: white;
color: black;
font-family: sans-serif;
}
button {
padding: 5px 10px;
cursor: pointer;
}
.error, #error {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Email validation example</title>
</head>
<body>
<form id="myForm" action="?" novalidate="">
<label for="email">Email:</label>
<input type="email" id="email" required=""/>
<span class="error">* <span id="error"></span></span>
<br/><br/>
<button type="submit">Submit</button>
</form>
</body>
</html>
A: Notice the y.validationMessage in the javascript part of the code. It logs the default html5 input validation messages into the <span> element(If you run the snippet, then you might know).
B: My question is: Is there a way where we can make angularjs log the default html5 input validation message like how the validationMessage property did?
You can try Like that
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email" ng-model="email" required=""/>
<span ng-show="myForm.email.$dirty && myForm.email.$error.required">Email is required.</span>
<br/><br/>
<button type="submit">Submit</button>
</form>
Sample

Can somebody help me with a non functioning javascript code for the most unsafe login page?

I need to make a login page on my website with the html and JavaScript.
This is what I have tried so far
</div>
<ul class="login-list">
<li><h2>Member login</h2></li>
<li><input type="text" name="Username" placeholder="Username"></li>
<li><input type="password" name="Password" placeholder="Password"></li>
<li><input type="button" onclick="login();" name="Login" value="Login"></li>
<li>Forgot Password?</li>
</ul>
</div>
<script language="javascript">
function login() {
if(li.Username.value == "admin" && li.Password.value == "welcome")
{
window.open('dashboard.html')
}
else {
alert("The username and password don not match.")
}
}
</script>
Also, I am very much aware of this being the most unsafe way of creating a login page but it does not really matter for my purpose.
I would like for it to output an alert if the input is wrong. When
the input is right I want it to route the user to the
dashboard.html file.
You are trying to access the text in the input element incorrectly. You should try:
var userName = document.getElementsByName('Username')[0].value;
var passWord = document.getElementsByName('Password')[0].value;
if(userName == "admin" && passWord == "welcome")
{
window.open('dashboard.html')
}
else {
alert("The username and password don not match.")
}
document.getElementsByName() returns a NodeList, so you have to access it by an index: document.getElementsByName('staff_counter')[0] (depending on how many of these you have). Refrence
You're referencing the first element in that NodeList of that name that is why its [0]
The code below may be more helpful incase you plan to implement actual server side logic.
it will also work great for your demo. I tried to minimize the css use
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<style type="text/css">
div{
border: 5px solid white;
margin:20px;
width: 252px;
}
.page_center{
width: 300px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="page_center">
<div>
<form action="" method="">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="username_input" placeholder="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password_input" placeholder="password"></td>
</tr>
</table>
</form>
</div>
<div style="text-align: center;">
<input type="submit" name="submit_button" value="Login" onclick="Login()">
</div>
<div style="text-align: center;">
Forgot Password?
</div>
</div>
<script type="text/javascript">
function Login(){
var username = document.getElementsByName("username_input")[0].value;
var password = document.getElementsByName("password_input")[0].value;
if (username == "admin" && password == "welcome") {
window.open('dashboard.html')
}else {
alert("The username and password do not match.");
}
}
</script>
</body>
</html>

How to take html input and display it using external javascript

I have coded a pretty basic page to collect student information (first name, last name, semester, and course name). The first and last name are input type="text"s and the semester and course name are drop down lists.
I now need to use an external JS file to take the text stored in the inputs and display them under registered course as
"First Name Last Name is registered for the following course:
Semester:
Course:"
This is the html code I wrote
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>University Registration</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<div class="headerContainer">
<h1>University Registration System</h1>
</div>
</header>
<form action="" method="get" class="scInfo">
<h3>Student and Course Info:</h3>
<div class="fn">
<p>First Name: </p>
<input type="text" name="fn" id="fn" required>
</div>
<div class="ln">
<p>Last Name: </p>
<input type="text" name="ln" id="ln" required>
</div>
<div></div>
<div class="semester">
<p>Semester: </p>
<select>
<option value="fall">Fall 2019</option>
<option value="spring">Spring 2020</option>
</select>
</div>
<div class="course">
<p>Course Name: </p>
<select>
<option value="365">CIS 365 - Business Database Systems</option>
<option value="425">CIS 425 - Enterprise Web Technologies</option>
</select>
</div>
<div class="button">
<button id="register">Register</button>
</div>
</form>
<h3>Registered Course:</h3>
<div class="nameOutput">
</div>
<div class="semesterOutput">
</div>
<div class="classOutput">
</div>
<script src="script.js"></script>
</body>
</html>
this is the css code I wrote
header h1
{
text-align: center;
padding: 10px;
border-bottom: 1px solid black;
}
form .fn
{
display: inline-block;
padding: 5px;
}
form .ln
{
display: inline-block;
padding: 5px;
}
form .semester
{
display: inline-block;
padding: 5px;
}
form .course
{
display: inline-block;
padding: 5px;
}
form .button
{
padding: 5px
}
No need to show the CSS file, as it's not relevant here. This entirely depends on what backend you are using, because you need to get the user to register successfully first, before you output anything onto the screen.
One way to do this, is if you're using a backend API (also you need a POST method, not GET):
<form id="registerForm">
...
<input type="submit" value="registerBtn" name="Register" role="button" id="registerBtn">Register Now</button>
In your javascript file, you can use an event handler to get the data, send it to your backend API to register the user, and if you get a 200 status code or any equivalent success code, you can display the info back to the user
In your javascript file:
const registerForm = document.querySelector("#registerForm")
registerForm.addEventListener("submit", (e) => {
e.preventDefault(); //prevent form from resetting the page
// grab the input values, and use a request package like axios or javascript's native xmlhttprequest to send the data
});
If you want to extract the value from the form itself, then follow the code below.
I have made some changes to your div and select as well.
const form = document.getElementById('registerForm');
form.addEventListener('submit', (event) => {
event.preventDefault();
let full_name = document.getElementById('fn').value + ' ' + document.getElementById('ln').value;
let name = document.getElementsByClassName('nameOutput')[0];
name.innerHTML = full_name + 'is registered for the following course';
let sem = document.getElementById('semester');
val_sem = sem.options[sem.selectedIndex].text;
let semester = document.getElementsByClassName('semesterOutput')[0];
semester.innerHTML = val_sem;
let cls = document.getElementById('course');
val_cls = cls.options[cls.selectedIndex].text;
let classOutput = document.getElementsByClassName('classOutput')[0];
classOutput.innerHTML = val_cls;
});
<header>
<div class="headerContainer">
<h1>University Registration System</h1>
</div>
</header>
<form action="" method="get" class="scInfo" id="registerForm">
<h3>Student and Course Info:</h3>
<div class="fn">
<p>First Name: </p>
<input type="text" name="fn" id="fn" required>
</div>
<div class="ln">
<p>Last Name: </p>
<input type="text" name="ln" id="ln" required>
</div>
<div></div>
<div class="semester">
<p>Semester: </p>
<select id="semester">
<option value="fall">Fall 2019</option>
<option value="spring">Spring 2020</option>
</select>
</div>
<div class="course">
<p>Course Name: </p>
<select id="course">
<option value="365">CIS 365 - Business Database Systems</option>
<option value="425">CIS 425 - Enterprise Web Technologies</option>
</select>
</div>
<div class="button">
<button id="register">Register</button>
</div>
</form>
<h3>Registered Course:</h3>
<div class="nameOutput">
</div>
<div class="semesterOutput">
</div>
<div class="classOutput">
</div>
I could not insert a external js into the code snippet.But you can just copy the below js into a file and call the file below the same way you have done in your code above.
The output will be displayed when the form will be submitted.There are even better ways to do this, but this is the basic way to achieve it, and also if you are new this will give you some understanding of selectors as well.
Make sure you go through the js code.
Hope this helps
Thanks

Form submit not working in safari and works in all other browsers?

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link rel="icon" type="image/png" href="images/fav_icon.png">
<script>
function submitAlbum(){
var frm=document.getElementById("custRegistration");
frm.action="CustomerinfoServlet?formidentity=domobileappRegistrations";
frm.submit();
}
</script>
</head>
<body style=" background-color:#f9f9f9" onload="DrawCaptcha();">
<!--start mainwrap-->
<div id="mainwrap">
<!--start midwrap-->
<div id="midwrap">
<div style="width: 100%; background-repeat:no-repeat; margin-top:15px; height:546px; background-image: url('images/form_background.png')">
<br/><br/><br/>
<div style="margin: 0 auto; background-color: #ffffff; opacity:0.9; border: 1px solid #D7EBFF; width: 400px; padding: 15px; height: 440px; margin-left: 56%;">
<form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" >
<p class="name">
<label for="name">Name <span style="color:red">*</span>:</label>
<input type="text" name="name" id="name" placeholder="" pattern="[A-Za-z ]{3,20}" required/>
<input type="hidden" id="formidentity" name="formidentity" value="domobileappRegistrations"/>
</p>
<p class="email">
<label for="email">Email Id <span style="color:red">*</span>:</label>
<input type="email" name="email" id="email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|org|net|us|info|biz|co)" required aria-required="true" placeholder="" required/>
</p>
<p class="submit">
<label for="download" id="freetrail"></label>
<input type="submit" value="Submit" />
</p>
</form>
</div>
</div>
</div>
</div>
<div style="clear:both"></div>
</body>
</html>
Above form is working fine in all the browsers except safari(version used is-5.1.7) and iPad.In safari the form is not validating the html5 required attribute and making the form to submit, while in other browsers(chrome,firefox,IE) its working fine.so can anyone tell me how can i make it done with safari??any help would be appreciated..
The HTML form validation is a Working Draft.
It is a method of setting required fields and field types without requiring JavaScript.
Partial support in Safari refers to lack of notice when form with required fields is attempted to be submitted. Partial support in IE10 mobile refers to lack of warning when blocking submission.
Also support for using differently colored borders is not complete in Firefox or Opera - using a separate class for styling works well in both.
In Chrome the attribute formnovalidate doesn't work on <input type="submit"> elements but does on <button type="submit"> elements.
You can try to use the script bellow for all browsers not supporting HTML5 required attribute:
//Required attribute fallback
$('#form').submit(function() {
if (!attributeSupported("required") || ($.browser.safari)) {
//If required attribute is not supported or browser is Safari
//(Safari thinks that it has this attribute, but it does not work),
//then check all fields that has required attribute
$("#form [required]").each(function(index) {
if (!$(this).val()) {
//If at least one required value is empty, then ask to fill all required fields.
alert("Please fill all required fields.");
return false;
}
});
}
return false; //This is a test form and I'm not going to submit it
});
EDIT:
As alternative, you can use the jQuery validation plugin, in such basic way (more details on how-to use it are if you follow the link):
$(document).ready(function() {
// validate the form when it is submitted
$("#form").validate();
});
This is the most browser's compatible solution.

Categories