How to print input from a text field? - javascript

I've been trying to make a simple login system (local) and I'm a bit confused.. How can I take the input the user wrote into the text field print it in console and store it in a variable?
My HTML code:
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="username.js"></script>
<script src="password.js"></script>
</head>
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form name="">
<label for="text1">Username:</label>
<input type="text" name="text1">
<label for="text2">Password:</label>
<input type="text" name="text2">
<button onclick="password(), username()">login</button>
</form>
</body>
</html>
For my JS I wanted to have the ''password() and username()'' functions checking both seperatly in seperate files.
JS Password file:
const Psword = 'Password9' //just an example
function password() {
console.log(Psword)
// if (user input from password field) = Psword
// alert('Login sucessfull redirecting!)
// else{
// alert('Username or password are incorrect')
// }
}
JS Username file:
var Username = 'Subject09'
function username() {
console.log(Username)
// if (user input from username field) = Username
// alert('Login sucessfull redirecting!)
// else{
// alert('Username or password are incorrect')
// }
}
EDIT: Added my JS code.
(Note: I've split my code into 2 diffrent JS files because I just want it to be simple in the outcome.)

We can do a form submit using onsubmit event.
UPDATE: I am showing you the form submit approach.
const form = document.querySelector("form");
form.addEventListener("submit",(e)=>{
e.preventDefault();
if(form["text1"].value && form["text2"].value){
console.log("Submitted the form");
form.reset();
}else{
console.log("Provide required values");
}
})
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="username.js"></script>
<script src="password.js"></script>
</head>
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form>
<div>
<label>Username:</label>
<input type="text" name="text1" >
</div>
<div>
<label>Password:</label>
<input type="text" name="text2">
<div>
<button type="submit">login</button>
</form>
</body>
</html>

Set ids to you input and your button. You can prevent submitting by adding type="button" to your button.
Simply set an onclick event on your button, and get your inputs values.
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form>
<label for="text1">Username:</label>
<input type="text" name="text1" id="username">
<label for="text2">Password:</label>
<input type="text" name="text2" id="password">
<button type="button" id="submitBtn">login</button>
</form>
window.onload = function() {
document.getElementById('submitBtn').addEventListener('click', onSubmit);
}
function onSubmit() {
console.log(document.getElementById('username').value);
console.log(document.getElementById('password').value);
// Do what you want with data
// You can submit with .submit()
document.forms['form'].submit();
}

Related

Opening a local HTML page through javascript

I have this html code where the index.html loads first. It has a text field and a submit button. When the submit button is clicked, it calls the validateForm() function. Suppose the text field is empty, it should alert that it is empty, if it isn't then a new html page would load (either in new tab or current one) which is supposed to be welcome.html
So my problem is, the welcome.html file isn't loading. I even changed the "welcome.html" in window.location.href = "welcome.html" to "https://www.google.com" . The page still wouldn't load. What's wrong and what am I missing here ?
Any help is appreciated.
index.html
<!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>Form</title>
<script src="/validateForm.js"></script>
</head>
<body>
<form method="get" onsubmit="return validateForm()">
Name: <input type="text" name="name" id="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
validateForm.js
function validateForm() {
var name = document.getElementById("name");
var nameData = name.value;
if (nameData == "" || nameData == null) {
alert("Name must be filled!");
}
else {
window.location.href = "welcome.html";
}
}
welcome.html
<!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>Welcome :)</title>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
Use action attribute
You can use the action attribute on the form to forward to a URL on success:
<form method="get" action="welcome.html" onsubmit="return validateForm()">
Name: <input type="text" name="name" id="name">
<input type="submit" value="Submit">
</form>
Documentation: MDN - Form action attribute
return value of validateForm()
See this?
onsubmit="return validateForm()"
Your validateForm doesn't return anything.
It is convention that return false means "stop processing the form" and a true-ish value means continue, which in turn means the action attribute mentioned above leads to welcome.html as you wanted.
The modified function could be this:
function validateForm() {
var name = document.getElementById("name");
var nameData = name.value;
if (nameData == "" || nameData == null) {
alert("Name must be filled!");
return false;
}
return true;
}
Alternatively, give validateForm a first parameter named event and call event.preventDefault() instead of returning false.
Documentation: MDN - Form submit handling example
You need some changes in index.html file and validateForm.js file
index.html
<form method="get" onsubmit="return validate()" action="javascript::window.location.replace('welcome.html')">
...
</form>
and in validateForm.js
you need to return true or false
after validation function if true it redirects to welcome.html or if false nothing were heppened.

How can I redirect users after they logged in with if/else statement (JavaScript)?

I am learning JavaScript so I decided to make a small project of simple if/else statement login. Everything is fine, but it is not redirecting.
If you know what I am doing wrong please help me in simple language
because I am learning it.
'use strict'
function validate(){
var username=document.getElementById('login-username').value;
var passowrd=document.getElementById('login-password').value;
if (username === "daksh" && passowrd === 'daksh'){
alert('You have sucessfully logged in');
window.location.href("http://stackoverflow.com");
} else{
alert('Wrong username or password');
return true;
}
}
<!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">
<link rel="stylesheet" href="login.css">
<title>Login</title>
<script src="login.js"></script>
</head>
<body>
<DIV class="container">
<form method="POST" class="login-form">
<h1 class="login-heading">LOGIN FORM</h1>
<input type="text" placeholder="User Name" id="login-username">
<br><br>
<input type="password" placeholder="Password" id="login-password">
<br><br><br>
<input type="submit" value="Login" id="login-submit" onclick="validate()">
</form>
</DIV>
</body>
</html>
ALWAYS use the submit event handler on a form, NEVER the submit button - you want to block the submission in case of error, or in your case blcok because you are handling the processing yourself
Use eventListener instead of inline event handler
You use location.href as a function, it is not. You could use location.replace(href) if you wish
For obvious security reasons, do not do client side passowrd validation, but I assume it is just for learning purposes
window.addEventListener("load", function() { // when the page has loaded
document.getElementById("myForm").addEventListener("submit", function(e) { // passing the event
e.preventDefault(); // you do not want to let the form submit because you handle the nex page
const username = document.getElementById('login-username').value;
const password = document.getElementById('login-password').value;
if (username === "daksh" && password === 'daksh') {
alert('You have sucessfully logged in');
window.location.href = "http://stackoverflow.com";
} else {
alert('Wrong username or 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">
<link rel="stylesheet" href="login.css">
<title>Login</title>
<script src="login.js"></script>
</head>
<body>
<div class="container">
<form method="POST" class="login-form" id="myForm">
<h1 class="login-heading">LOGIN FORM</h1>
<input type="text" placeholder="User Name" id="login-username">
<br><br>
<input type="password" placeholder="Password" id="login-password">
<br><br><br>
<input type="submit" value="Login" id="login-submit">
</form>
</div>
</body>
</html>
window.location.href is a property, not a method, so your code should be like:
window.location.href = "http://stackoverflow.com";
More info about it on MDN Web Docs
window.location.href is not a function.
You need to assign the url to window.location.href.
window.location.href = 'http://stackoverflow.com';
However, window.location.href simulates a click. If you want to simulate a HTTP redirect use window.location.replace instead.
window.location.replace('http://stackoverflow.com');
Edit:
You are also submitting the form, because there is a form method and a submit input specified. This triggers a form post and because no action is specified it will reload the page. Remove the form method and use a button instead.
function validate(){
var username=document.getElementById('login-username').value;
var passowrd=document.getElementById('login-password').value;
if (username === "daksh" && passowrd === 'daksh'){
alert('You have sucessfully logged in');
location.href = 'http://stackoverflow.com';
} else{
alert('Wrong username or password');
return true;
}
}
<!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>Login</title>
</head>
<body>
<DIV class="container">
<form class="login-form">
<h1 class="login-heading">LOGIN FORM</h1>
<input type="text" placeholder="User Name" id="login-username">
<br><br>
<input type="password" placeholder="Password" id="login-password">
<br><br><br>
<button type="button" value="Login" id="login-submit" onclick="validate()" value="login">Login</button>
</form>
</DIV>
</body>
</html>
This is what you should do as regards redirecting to another page using javascript
Here is the index.html page
<!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">
<link rel="stylesheet" href="login.css">
<script src="demo.js"></script>
<title>Login</title>
</head>
<body>
<div class="container">
<!-- Form was given an id of 'formLogin' which will be refernced from javascript. -->
<form method="POST" class="login-form" id="formLogin">
<h1 class="login-heading">LOGIN FORM</h1>
<input type="text" placeholder="User Name" id="login-username">
<br><br>
<input type="password" placeholder="Password" id="login-password">
<br><br><br>
<input type="submit" value="Login" id="login-submit" onclick="validate()">
</form>
</div>
</body>
</html>
From
demo.js
javascript file, the below code
'use strict'
// a function to validate the fields supplied from the form
function validate(e){
e.preventDefault(); // this is to prevent the form from refreshing on submitting
//getting the values from the textfields in the form
let username=document.getElementById('login-username').value;
let passowrd=document.getElementById('login-password').value;
// if the name and password matches the required credentials,
if (username === "daksh" && passowrd === 'daksh'){
alert('You have sucessfully logged in'); //display a successful login alert
location.href = "http://stackoverflow.com"; //redirect to the URL specified
} else{
alert('Wrong username or password'); // display alert for wrong credentials
return false;
}
}
// Here we are adding an event listener to the form in our index.html file
// When the form is submitted, the custom validate function is called.
document.getElementById('formLogin').addEventListener('submit', validate);
</script>

how to detect input language for creating slug, if not English then slug input remain empty using javascript

i am trying to take title input and create slug using it. But if the title is not written in English like "আমার প্রথম পোস্ট" then the slug input will remain empty. The code is given below. hope someone can help. Not good at javascript .
document.getElementById("title").addEventListener("keyup", function() {
if (/^[a-zA-Z]+$/.test(this.value)) {
$(document).on('blur', '#title', function(){
var TitleInput = $('#title').val().toLowerCase().trim();
TitleInput = TitleInput.replace(/[^a-z0-9-]+/g, '-');
var SlugInput = $('#slug').val(TitleInput);
});
} else {
document.getElementById("show_lang_in_here").innerHTML = "Different language";
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<center>
<h1>Form</h1>
<form action="" method="post">
<p>Title :</p>
<input id="title" type="text"> <br>
<br>
<p>Slug :</p>
<input id="slug" type="text">
</form>
<div id="show_lang_in_here"></div>
</center>
</body>
</html>
I have modified your code to do what I believe you're after, these are the main changes:
Wait for the document to be loaded with $(document).ready()
I've expanded your regex to allow numbers and spaces as valid English /^[a-zA-Z0-9 ]+$/ (There's a lot more you can add to this, it's quite difficult to detect exactly what is valid English)
You were creating an event listener inside your if, instead of actually executing the code (You can listen for multiple events by including them in the .on('keyup blur') string)
$(document).ready(function() {
$('#title').on('keyup blur', function() {
if (/^[a-zA-Z0-9 ]+$/.test($(this).val())) {
var titleInput = $(this).val().toLowerCase().trim().replace(/[^a-z0-9-]+/g, '-');
$('#slug').val(titleInput);
} else {
$('#show_lang_in_here').text('Different language');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<center>
<h1>Form</h1>
<form action="" method="post">
<p>Title :</p>
<input id="title" type="text"> <br>
<br>
<p>Slug :</p>
<input id="slug" type="text">
</form>
<div id="show_lang_in_here"></div>
</center>
What you are doing is replacing by -
If you want to remove everything, change it to TitleInput = TitleInput.replace(/[^a-z0-9-]+/g, '');
document.getElementById("title").addEventListener("keyup", function() {
if (/^[a-zA-Z]+$/.test(this.value)) {
$(document).on('blur', '#title', function(){
var TitleInput = $('#title').val().toLowerCase().trim();
TitleInput = TitleInput.replace(/[^a-z0-9-]+/g, '');
var SlugInput = $('#slug').val(TitleInput);
});
} else {
document.getElementById("show_lang_in_here").innerHTML = "Different language";
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<center>
<h1>Form</h1>
<form action="" method="post">
<p>Title :</p>
<input id="title" type="text"> <br>
<br>
<p>Slug :</p>
<input id="slug" type="text">
</form>
<div id="show_lang_in_here"></div>
</center>
</body>
</html>

Trying to learn to combine a form and script to affect my page

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>placeholder</h1>
<form method="get">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
<input type="submit">
</form>
<script type="text/javascript">
let actualWord = document.getElementById('word');
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
} else {
document.querySelector('h1').innerHTML = "error";
}
</script>
</body>
</html>
Im very new to the world of coding and im hoping someone could help me with a "simple" test I was trying to perform.
I want this HTML code to replace the "Placeholder" text at the top of the screen with "oh Yeah" if the user types "yes" in the form.
Im hoping someone can tell me what im doing wrong or point me in the right direction.
https://github.com/Uken81/Form-test.git
1.You need to listen to form submit event and trigger a function
HTML
<form onsubmit="return handleSubmit()">...</form>
Javascript
function handleSubmit(evt) {
...
}
2.You get user's input value like this
document.getElementById('word').value
3.Also you need to prevent form from submitting, By returning false
Full Example
function handleSubmit(evt) {
let actualWord = document.getElementById('word').value;
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
}
return false;
}
<h1>placehold</h1>
<form onsubmit="return handleSubmit()">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
</form>
You can achieve that by adding click event listener to the <submit> button inside the form, and then perform the check on the text <input> and use .value attribute to get the <input> text value, note that I used [e.preventDefault()][3] to prevent the form from redirect, here is a working snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>placeholder</h1>
<form method="get">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
<input id="change-placeholder" type="submit">
</form>
<script type="text/javascript">
document.getElementById('change-placeholder').addEventListener('click', function(e){
e.preventDefault();
let actualWord = document.getElementById('word').value;
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
} else {
document.querySelector('h1').innerHTML = "error";
}
})
</script>
</body>
</html>

How could i clear my input field but push my data to database?

I'm trying to clear my input field's ,but when i clear them php pushes empty string to my database .could someone help me?
this is my code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'phpAdd.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
function submitForm(){
var form = document.getElementById("myForm");
form.reset();
$('#firstname').focus();
}
</script>
</head>
<body>
<center>
<form action="phpAdd.php" method="post" id="myForm">
<h1>Please enter your info.</h1>
First Name: <input type="text" name="firstname" id="firstname" class="firstname"><br>
Last Name: <input type="text" name="lastname" id="lastname" class="lastname"> <br>
<input type="submit" value="SUBMIT" class="SUBMIT" onclick="submitForm()">
</form>
</center>
</body>
</html>
how could i clear the field's after it pushes the data to php?

Categories