I am trying to get my code to check if the value submitted in "username" already exist in "usernames" list. If it does, would like to have the message displayed and if it does not, add that value to the "usernames" list and submit form.
Don't understand why my code doesn't work. Please see below:
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Validating Form Data</title>
<link rel="stylesheet" href="index.css" type="text/css">
</head>
<body>
<h3>Register your account:</h3>
<p id="errors"></p>
<form id="registration-form" method="POST" action="https://formdump.codeinstitute.net/">
<div class="username">
<label for="username">Username:</label>
<input id="username" name="username" type="text" required>
</div>
<div class="password">
<label for="password">Password:</label>
<input id="password" name="password" type="password" required>
</div>
<input type="submit">
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.js" integrity="sha256-DrT5NfxfbHvMHux31Lkhxg42LY6of8TaYyK50jnxRnM=" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
CSS
label {
display: block;
}
input {
margin-bottom: 1rem;
}
p {
color: red;
font-weight: bold;
}
JS
let usernames = ["Harry", "Daisy", "Michael", "Sarah", "Sally"];
// Write your code here
let form = document.getElementById("registration-form");
form.addEventListener("submit", handleSubmit);
let errorMsg = document.getElementById("errors");
let uName = form.elements["username"].value;
let abc = usernames.includes(uName);
function handleSubmit(event) {
event.preventDefault();
if (abc) {
errorMsg.innerHTML = `<p>Sorry, the username ${uName} is already in use. Please choose another username.</p>
`;
} else {
usernames.push(uName);
form.submit();
console.log(usernames);
}
}
I tried replacing includes() with indexOf(), but still doesn't work.
As I said in the comment,you need to get the input value correctly each time it submit,so needs to put below code inside handleSubmit,otherwise uName will be null and abc will always be false(due to it execute before submiting)
let uName = form.elements["username"].value;
let abc = usernames.includes(uName);
let usernames = ["Harry", "Daisy", "Michael", "Sarah", "Sally"];
// Write your code here
let form = document.getElementById("registration-form");
form.addEventListener("submit", handleSubmit);
let errorMsg = document.getElementById("errors");
function handleSubmit(event) {
event.preventDefault();
let uName = form.elements["username"].value;
let abc = usernames.includes(uName);
if (abc) {
errorMsg.innerHTML = `<p>Sorry, the username ${uName} is already in use. Please choose another username.</p>
`;
} else {
usernames.push(uName);
form.submit();
console.log(usernames);
}
}
label {
display: block;
}
input {
margin-bottom: 1rem;
}
p {
color: red;
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Validating Form Data</title>
<link rel="stylesheet" href="index.css" type="text/css">
</head>
<body>
<h3>Register your account:</h3>
<p id="errors"></p>
<form id="registration-form" method="POST" action="https://formdump.codeinstitute.net/">
<div class="username">
<label for="username">Username:</label>
<input id="username" name="username" type="text" required>
</div>
<div class="password">
<label for="password">Password:</label>
<input id="password" name="password" type="password" required>
</div>
<input type="submit">
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.js" integrity="sha256-DrT5NfxfbHvMHux31Lkhxg42LY6of8TaYyK50jnxRnM=" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
Related
I'm making a code where the user enters information and it stores it in an object, but when I check if the object is saved by alerting one of its values it says there is no such object.
here is my code.
let users = {};
function user(name,real){
this.username = name,
this.realname = real,
this.id = Math.floor(Math.random() *1000);
this.subs = 0,
this.videos = [],
this.listuser = function() {
return this.username;
}
};
function newuser(name, email,username){
users[name] = new user(username, name);
};
let savefile = () => {
var channame = string(document.getElementById('channame'));
var name = string(document.getElementById('name'));
var email = string(document.getElementById('email'));
newuser(name,email,channame);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>youtube ripoff</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<br> <br><br><br><br><br>
<form action="">
<label for="username">Channel Name: </label>
<input type="text" id="channame" name="channelname"><br>
Real Name
<input type="text" id="name" name="name"><br>
Email
<input type="text" id="email" name="email"><br>
<input type="submit" value="Submit" onmousedown="newuser('name1','name#gmail.com','channelname1');">
<br><br><br><br>
<input type="button" value="Load Channels" id="seech" name="seechannels" onmousedown="alert(users['name1'].listuser());"><br>
</form>
<script src="script.js">
function fun(){
window.alert("starting program...")
//other code
}
</script>
</body>
</html>
Is there some sort of error that I'm not seeing?
After click on submit button in form with action="" page is reload and all data is lost. Pleas use:
<form action="javascript:void(0)">
instead of
<form action="">
This prevent page reload.
I am making a registration form. I have finished making the registration form, but I just need to add one more thing to the registration form: a button that adds text to the registration form. How do I make that button appear in the text input? Can someone help? Here is a runnable current snippet of the registration form:
function ValidationForm() {
let username = document.forms["RegForm"] ["Name"];
let email = document.forms ["RegForm"] ["Email"];
let phoneNumber = document.forms ["RegForm"] ["Telephone"];
let pass = document.forms ["RegForm"] ["Password"];
if (username.value == "") {
alert("Please enter your name.");
username.focus();
return false;
}
if (email.value == "") {
alert("Please enter a valid email address.")
email.focus();
return false;
}
if (phoneNumber.value == "") {
alert("Please enter your telephone number.")
phoneNumber.focus();
return false;
}
if (pass.value == "") {
alert("Please enter your password.")
pass.focus();
return false;
}
return true;
}
.regform {
margin-left: 70px;
font-weight: bold;
text-align: left;
font-family: sans-serif, bold, Arial, Helvetica;
font-size: 14px;
}
.buttons {
display: flex;
align-items: center;
width: 100%;
}
div input {
margin-right: 10px;
}
form {
margin: 0 auto;
width: 600px;
}
form input {
padding: 10px;
}
form label {
display: block;
width: 100%;
margin-bottom: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
<script src="script.js" defer></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2 style="text-align: center;"> Registration Form </h2>
<form name="RegForm" action="hidden for no hackers" onsubmit="return ValidationForm()" method="POST" class="regform">
<div>
<label for="Name">Name:</label>
<input type="text" id="Name" size="60" name="Name">
</div>
<br>
<div>
<label for="E-mail">E-mail Address:</label>
<input type="email" id="E-mail" size="60" name="Email">
</div>
<br>
<div>
<label for="Password">Password:</label>
<input type="password" id="Password" size="60" name="Password">
</div>
<br>
<div>
<label for="Telephone">Telephone:</label>
<input type="tel" id="Telephone" size="60" name="Telephone">
</div>
<br>
<div class="buttons">
<input type="submit" value="Send" name="Submit">
<input type="reset" value="Reset" name="Reset">
</div>
</form>
</body>
</html>
Here is a "button that adds text":
document.getElementById("btn").addEventListener("click", () => {
document.getElementById("input").value += "Text";
});
<button id="btn">Click to add text to input below</button>
<br /><br />
<input id="input" />
Today I am going to use JavaScript to do a validation of the registration page, but after an afternoon of verification, the function can be called. When the test pop-up window is added at the beginning of the function, the pop-up window pops up correctly, but the verification function in the function is always unresponsive. Ask for the forum's amnesty, where is the problem, thank you! ! !
I added a test popup statement to the script and it succeeded. But other functions don't respond.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册界面</title>
<link rel="stylesheet" type="text/css" href="css/register.css">
<script type="text/javascript">
window.alert("test");
function checkRegisterINfo(form) {
/*判断姓名格式是否正确*/
var RegisterNameCheck = document.getElementById("nameId").value;
if (RegisterNameCheck = "") {
window.alert("姓名不能为空!");
return false;
} else {
var rightName = /[\u4E00-\u9FA5]{2,16}/;
if (rigntName.test(RegisterNameCheck) == true) {} else {
window.alert("您输入的姓名不正确!");
return false;
}
}
/*判断密码是否规范*/
var RegisterPwdCheck = document.getElementById("pwdId").value;
var rightPwd = /^(\w){6,20}$/;
if (rightPwd.test(RegisterPwdCheck) == false) {
window.alert("密码只能输入6-20个字母、数字、下划线");
return false;
}
/*判断密保问题格式是否正确*/
var RegisterQuestionCheck = document.getElementById("questionId").value;
var rightQuestion = /[\u4E00-\u9FA5]{1,16}/;
if (!rightQuestion.test(RegisterQuestionCheck)) {
window.alert("密保问题支持1-16位汉字!");
return false;
}
/*判断密保答案格式是否正确*/
var RegisterAnswerCheck = document.getElementById("answerId").value;
var rightAnswer = /[\u4E00-\u9FA5]{1,50}/;
if (!rightAnswer.test(RegisterAnswerCheck)) {
window.alert("密保答案支持1-50位汉字!");
return false;
}
}
</script>
</head>
<body>
<div class="main">
<div class="title">
<span>用户注册</span>
</div>
<form name="registerForm" method="post" action="" onsubmit="return checkRegisterINfo(registerForm)">
<!--输入框-->
<div class="input-content">
<div>
<input type="text" autocomplete="off" id="nameId" placeholder="用户名" name="Registerusername" required/>
</div>
<div style="margin-top: 16px">
<input type="password" autocomplete="off" id="pwdId" placeholder="登录密码" name="Registerpassword" required maxlength="32" />
</div>
<div style="margin-top: 16px">
<input type="text" autocomplete="off" id="questionId" placeholder="密保问题" name="Registerquestion" required maxlength="32" />
</div>
<div style="margin-top: 16px">
<input type="text" autocomplete="off" id="answerId" placeholder="密保答案" name="Registeranswer" required maxlength="32" />
</div>
</div>
<!--登入按钮-->
<div style="margin-top: 105px">
<button type="submit" class="enter-btn">登录</button>
</div>
<div class="foor">
<div class="left"><span>忘记密码</span></div>
<div class="right"><span>用户登录</span></div>
</div>
</form>
</div>
</body>
</html>
There are two codes. one works the other doesn't work.
I debugged it and I found that
"var eb = new EventBus("http://192.168.0.27:8081/bridge");"
this line in login.js doesn't work well.
Thank you so much everytime.
working
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//cdn.jsdelivr.net/sockjs/0.3.4/sockjs.min.js"></script>
<script src="vertx-eventbus.js"></script>
</head>
<style>
.news {
font-size: 20pt;
}
</style>
<body>
<div class="news">Latest news:</div>
<br>
<div id="status" class="news"></div>
<script>
var eb = new EventBus("http://192.168.0.27:8081/bridge");
eb.onopen = function() {
// set a handler to receive a message
eb.registerHandler('call', function(error, message) {
console.log('received a message: ' + JSON.stringify(message));
});
// send a message
eb.send('call', {name : 'tim', age : 587});
}
</script>
</body>
</html>
no working - login.html
<!DOCTYPE html>
<!--
login.html
-->
<html>
<head>
<meta charset="UTF-8">
<title>Flat HTML5/CSS3 Login Form</title>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form" id="loginForm">
<input type="text" id="username" placeholder="username" />
<input type="password" id="password" placeholder="password" />
<input class="submit" type="submit" title="Login" value="Login" onclick="check(this.form)" />
<p class="message">
Not registered? Create an account
</p>
</form>
</div>
</div>
<script src="js/login.js"></script>
</body>
</html>
login.js
document.write("<script src='https://code.jquery.com/jquery-1.11.2.min.js'></script>");
document.write("<script src='//cdn.jsdelivr.net/sockjs/0.3.4/sockjs.min.js'></script>");
document.write("<script src='/vertx-eventbus.js'></script>");
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.username.value != "" && form.password.value != "") {
var eb = new EventBus("http://192.168.0.27:8081/bridge");
eb.onopen = function() {
// set a handler to receive a message
eb.registerHandler('call', function(error, message) {
console.log('received a message: ' + JSON.stringify(message));
});
// send a message
eb.send('call', {name : 'tim', age : 587});
}
} else {
alert("Input Password or Username")/*displays error message*/
}
}
You have written
document.write("<script src='/vertx-eventbus.js'></script>");
differently than in the working code. There is an extra "/" before "vertx..". Could that be the problem?
So I made a simple javascript form validator which creates a box with the error message using DOM. But I can't figure out a way how to reset all these changes when i reset the form using
<button type="reset">
I would like to know how it's done please.
Thanks.
The Code
<html>
<head>
<script type="text/javascript">
function validate(){
var fname = document.getElementById("fname");
var surname = document.getElementById("surname");
if(fname.value === "" || fname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("fname").style.display = "block";
return false;
}
//Verify Last Name
if(surname.value === "" || surname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("surname").style.display = "block";
return false;
}
}//End Validate Function
</script>
<style type="text/css">
#sbody{
width: 100px;
height: 100px;
background-color: #f3f3f3;
display:none;
}
.vis{
display: none;
font-size: 12px;
}
</style>
</head>
<body>
<section id="sbody">
<span id="fner" class="vis">First Name is missing.</span>
<span id="lner" class="vis">Surame is missing.</span>
</section>
<form id="registerForm" method="POST" action="register.php" onsubmit="return validate()">
<label for="fname" class="labelStyle">First Name: </label>
<input id="fname" name="fname" type="text" value="">
<label for="surname" class="labelStyle">Surname: </label>
<input id="surname" name="surname" type="text" value="">
<button type="submit">Sign Up</button>
<button type="reset">Reset</button>
</form>
</body>
</html>
The browser cannot magically figure out what has to be done to reset the custom changes.
However you can listen to the reset event of the form using element.addEventListener.
DEMO
HTML
<form id="test">
<div id="errors-ct">The form has errors</div>
<button type="reset">Reset</button>
</form>
JS
//wait for the DOM to be ready
document.addEventListener('DOMContentLoaded', function () {
//store a reference to the errors container div
var errorsCt = document.getElementById('errors-ct');
//listen to the reset event of the form
document.getElementById('test').addEventListener('reset', function (e) {
var form = e.target; //this is how you could access the form
//hide the errors container
errorsCt.style.display = 'none';
});
});
If you want to reset the form, as if user hadn't made any selections or added any input, then just set all form element values to their default value, or empty.
jsFiddle
<div>
<form action="/echo/html" method="get">
<input type="text" placeholder="username" />
<br/>
<input type="password" placeholder="password" />
<br/>
<input type="checkbox" value="test" data-default="checked" checked="checked"/>
<br/>
<button type="reset" value="reset" onclick="resetForm()">reset</button>
<br/>
</form>
<div id="err">Some error message</div>
</div>
window.resetForm = function () {
var fields = $('input'),
uname, pass, check;
uname = $(fields.get(0));
pass = $(fields.get(1));
check = $(fields.get(2));
$("#err").text("");
uname.val('');
pass.val('');
if (check.attr("data-default") == "checked") {
check.attr("checked", "checked");
} else {
check.removeAttr("checked");
}
}