Check the answer - javascript

I try to see if the word entered in the form is the correct one. If it is correct then I open another page and otherwise I will get an error message, but I don't know how to make the script for this. Also I don't want to use a submit button.
<form id="form">
<input type="text" name="inputBox" placeholder="Enter your answer"><br>
</form>

Try this:
In this code I check with the key event, if I press enter I call and ask if the answer is "Hello" is correct and I open another page, otherwise I send an alert with an error
<form id="form">
<input id="MyEnter" type="text" name="inputBox" placeholder="Enter your answer"><br>
</form>
<script>
var myenter = document.getElementById("MyEnter");
myenter.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
var answer = 'Hello'
var mytext = document.getElementById("MyEnter").value;
if (mytext==answer) {
alert('opening another page');
window.open("https://www.google.com");
}else{
alert("Incorrect answer");
}
}
});
</script>

const input = document.querySelector('input');
const error = document.querySelector('p.error');
const woohoo = document.querySelector('p.woohoo');
const correctAnswer = 'foo bar baz';
const handleInput = (condition) => {
if (condition) {
error.style.display = 'block';
woohoo.style.display = 'none';
return;
}
error.style.display = 'none';
woohoo.style.display = 'block';
window.open('https://google.com');
};
input.addEventListener('keyup', () => handleInput(input.value !== correctAnswer));
<form id="form">
<input type="text" name="inputBox" placeholder="Enter your answer" />
<p class="error" style="color: red; display: none">Incorrect</p>
<p class="woohoo" style="color: green; display: none">Correct</p>
</form>

Related

When button is submitted it returns a 404 error?

Here is my code.
Adding both the HTML and Javascript to get a clear understanding of what I did so someone can see where I went wrong
HTML
<form id="form" onsubmit="return addUser()">
<h2>Add a User:</h2>
<input id="name" type="text" name="username" placeholder="name">
<input id="email" class="mail" type="email" name="email" placeholder="email" onkeydown="validate()">
<span id="text"></span>
<button type="submit">Add User</button>
<h2>Users:</h2>
<ul id="users"></ul>
</form>
Javascript
It works fine in my local environment but when submitted in jsfiddle it returns a 404 error
function validate() {
let form = document.getElementById('form');
let email = document.getElementById('email').value
let eData = /^(([^<>()[\]\.,;:\s#\"]+(\.[^<>()[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
let text = document.getElementById('text')
if (email.match(eData)) {
form.classList.add('valid')
form.classList.remove('invalid')
text.innerHTML = "Your Email is Valid"
text.style.color = 'green'
} else {
form.classList.remove('valid')
form.classList.add('invalid')
text.innerHTML = "Please Enter Valid Email"
text.style.color = 'red'
}
if (email == '') {
form.classList.remove('valid')
form.classList.remove('invalid')
text.innerHTML = ''
text.style.color = '#00e5ff'
}
}
const list = document.getElementById('users')
function addUser() {
let newName = document.getElementById('name').value
let newMail = document.querySelector('.mail').value
let data = document.createElement('li')
data.appendChild(document.createTextNode(newName + ' ' + newMail))
list.appendChild(data)
return false;
}
// END YOUR CODE HERE
jsfiddle for reference
http://jsfiddle.net/m3c5djbf/25/
I thought my comment might not be clear enough so here you can see an implementation of preventing the form from sending an ajax request and breaking your app:
<html>
<body>
<form id='form'>
<label>test button</label>
<input type='submit' value='button?' />
</form>
<p id='text'>not clicked</p>
<script>
const form = document.getElementById('form');
const text = document.getElementById('text');
form.addEventListener('submit', e => {
e.preventDefault();
console.log('submitted?');
text.innerHTML = 'clicked';
})
</script>
</body>
</html>

How to delay redirect after onclick in javascript?

I am trying to delay the redirect of my page so that the success message can be seen. So far I have not had any luck in getting it. I have tried to stop it with setTimeout with the location.href but that doesn't seem to be working. Can someone point me in the right direction?
//Form
<form class="form" action="/" method="GET">
<div class="alert"></div>
<input type="text" class="textfields name" name="name" required placeholder="Name">
<input type="email" class="textfields email" name="email" required placeholder="Email">
<textarea class="message" placeholder="Your Message..."></textarea>
<button type="submit" class="footbtn">Send</button>
</form>
// Code
footBtn.addEventListener('click', (e) => {
const alertMessage = document.querySelector('.alert');
const email = document.querySelector('.email').value;
const name = document.querySelector('.name').value;
if (name === '' || email === '') {
alertMessage.innerHTML = 'Name/Email Required';
alertMessage.style.padding = '10px';
alertMessage.style.color = 'red';
e.preventDefault();
} else {
alertMessage.innerHTML = 'Thanks! Someone will be in touch with you soon!';
alertMessage.style.color = 'black';
alertMessage.style.padding = '10px';
alertMessage.style.textAlign = 'center';
}
})
You need to prevent the default action and manually submit the form after a delay. Also, listen for the submit event of the form instead of the click event on the submit button.
let form = document.querySelector('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const alertMessage = document.querySelector('.alert');
const email = document.querySelector('.email').value;
const name = document.querySelector('.name').value;
if (name === '' || email === '') {
alertMessage.innerHTML = 'Name/Email Required';
alertMessage.style.padding = '10px';
alertMessage.style.color = 'red';
} else {
alertMessage.innerHTML = 'Thanks! Someone will be in touch with you soon!';
alertMessage.style.color = 'black';
alertMessage.style.padding = '10px';
alertMessage.style.textAlign = 'center';
setTimeout(()=>form.submit(), 700);
}
})

How I can display the form data in the same page without submit the form?

I have a form in HTML and I want to display the form text input data on the same page but before pressing the submit button.
Mean, When Users put the data in the form it must display below the form on same page.
It's mean that I want to show all data before submitting the form.
I know this code will not work as i want
var strText = document.getElementById("textone");
document.write(strText.value);
var strText1 = document.getElementById("textTWO");
document.write(strText1.value);
}
This is how I would do it by directly manipulating the DOM:
const input = document.getElementById('textInput');
const textElement = document.getElementById('displayText');
function updateValue(e) {
textElement.textContent = e.target.value;
}
input.addEventListener('input', updateValue);
<input type="text" id="textInput">
<p>value from input:</p>
<div id="displayText"></div>
There are also javascript libraries like VueJS and ReactJS that can help you do this more easily and efficiently.
This is an example of something like what you would want to do in VueJS: https://v2.vuejs.org/v2/examples/index.html
I've prepared an example of general functioning, I hope you like it. It may not be exactly what you want, but if it is, please tell me.
const myForm = document.getElementById("myForm");
const nameInput = document.getElementById("nameInput");
const emailInput = document.getElementById("emailInput");
const nameOutput = document.getElementById("nameOutput");
const emailOutput = document.getElementById("emailOutput");
let nameSpan = document.getElementById("name");
let emailSpan = document.getElementById("email");
myForm.addEventListener("submit", e => {
e.preventDefault();
alert(`NAME: ${nameInput.value}, EMAİL : ${emailInput.value}`)
// select name , mail
nameSpan.innerText = nameInput.value;
emailSpan.innerText = emailInput.value;
// clear ınputs
nameInput.value = "";
emailInput.value = ""
})
showData();
function showData() {
nameInput.addEventListener("keyup", e => {
nameOutput.value = e.target.value;
})
emailInput.addEventListener("keyup", e => {
emailOutput.value = e.target.value;
})
}
<form id="myForm">
<input type="text" id="nameInput" placeholder="your name">
<input type="text" id="emailInput" placeholder="your email">
<button type="submit" id="getInputValue"> Get Input Value </button>
</form>
<div id="values" style="margin-top: 100px;">
<input type="text" placeholder="NAME" id="nameOutput">
<input type="text" placeholder="EMAİL" id="emailOutput">
</div>
<div>
<p>Your name : <span id="name"></span></p>
<p>Your email : <span id="email"></span></p>
</div>

Javascript errors when calling

I have read and tried everything I can think of. The other pages that look identical with calling the function onclick work fine. I have tried all I know and read extensively with no avail.
<html>
<head>
<title>Password</title>
</head>
<body>
<div id="output"></div>
<input id="playername" placeholder = "Username" /> <br>
<input id="password" placeholder = "Enter Password"/>
<button onclick="test()">Are you correct?</button>
<script src="pword.js"></script>
</body>
JS:
function test() {
let output = document.querySelector("#output");
let playername = document.querySelector("#playername");
let password = document.querySelector("#password");
if output.value === ("username") && password.value === ("Pa$$w0rd") {
console.log("CORRECT!");
} else {
console.log("Incorrect, try again");
}
}
You forgot a bracket during your if statement
if HERE => ( output.value === ("username") && password.value === ("Pa$$w0rd") ) <= AND HERE {
console.log("CORRECT!");
} else {
console.log("Incorrect, try again");
}
And it's better to do something like this, remove you'r onclick on HTML and do this :
HTML :
<button id="MyButton">Are you correct?</button>
JS :
var MyBtn = document.getElementById("MyButton");
MyBtn.addEventListener("click", test);
if (playername.value === "username" && password.value === "Pa$$w0rd") {
console.log("CORRECT!");
} else {
console.log("Incorrect, try again");
}
You're checking output.value instead of playername.value and the parenthesis are misplaced, here's a snippet with fixed code :
function test() {
let output = document.querySelector("#output");
let playername = document.querySelector("#playername");
let password = document.querySelector("#password");
if (playername.value === "username" && password.value === "Pa$$w0rd") {
console.log("CORRECT!");
} else {
console.log("Incorrect, try again");
}
}
<div id="output"></div>
<input id="playername" placeholder="Username" /> <br>
<input id="password" placeholder="Enter Password" />
<button onclick="test()">Are you correct?</button>
You are checking output.value instead of playername.value.
You can have a look at the working code here: https://repl.it/repls/ImaginaryCandidPerformance

what is the correct way to validate form with javascript

should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp

Categories

Resources