Incorrect & Correct statement - javascript

I need help to finish my incorrect & correct statement.
It shows both incorrect and correct every time I answer the question.
submitButton.addEventListener("click", function(event) {
event.preventDefault()
let useAnswer = document.querySelector('input').value.toLowerCase()
if (useAnswer === currentClue.answer.toLowerCase()) {
console.log('correct')
} else {
console.log('incorrect')
}
});
<form>
<div id="question"></div>
<input id="answer_input" type="answer" placeholder="Enter Answer" required/>
<button id="submit-button" type="submit">Submit</button>
</form>
<div class="result">
<p class="result_success">Correct</p>
<p class="result_fail">Incorrect</p>
<p class="result_correct-answer"></p>
</div>

I changed the event listener to listen for the submit event (you already had the event.preventDefault() that prevent the submit of the form) on the form. I gave both the form and input element a name.
var currentClue = {answer: "Test"};
document.forms.form01.addEventListener("submit", function(event) {
event.preventDefault();
let useAnswer = event.target.answer_input.value.toLowerCase();
if (useAnswer === currentClue.answer.toLowerCase()) {
console.log('correct');
} else {
console.log('incorrect');
}
});
<form name="form01">
<div id="question"></div>
<input id="answer_input" name="answer_input" type="answer" placeholder="Enter Answer" required/>
<button id="submit-button" type="submit">Submit</button>
</form>
<div class="result">
<p class="result_success">Correct</p>
<p class="result_fail">Incorrect</p>
<p class="result_correct-answer"></p>
</div>

Related

Unintentional popup FORM closing when clicking on a BUTTON or on a INPUT ( with JS code)

I'm finding a strange behaviour in a popup FORM when I click on a BUTTON (that operates on some object using a JS code), and on a INPUT (used for submit): in both cases, the form closes, and it is an unexpected action.
Probably is due to something very easy and common that I'm not fixing, but i can't find it.
This is the HTML interested part:
<form name="contactform" id="contactform" class="contact-form">
<div class="contactform-container">
<div class="common">
<label for="name">Nome</label>
<input type="text" id="name" name="name" />
</div>
<div class="common">
<label for="name">Cognome</label>
<input type="text" id="familyName" name="familyName" />
</div>
<div class="common">
<label for="email">e-mail</label>
<input type="text" id="email" name="email" />
</div>
<div class="message">
<label for="message">Annotazioni</label>
<textarea name="message" id="message" class="message"></textarea>
</div>
<div class="passRow">
<fieldset class="validatePass">
<div class="formGroup">
<label class="formLabel"for="password">Password
<span class="passErr"></span>
</label>
<div class="passWrapper">
<input type="password"
id="password"
class="form-control input-md"
name="password"
placeholder="Enter your password">
<span class="showPass">
<i class="fas fa-eye-slash"></i>
</span>
</div>
<p class="progress">Livello di sicurezza</p>
<div id="progressBar">
<div></div>
</div>
<ul id="progressList">
<li>Un carattere minuscolo e uno maiuscolo</li>
<li>Un numero</li>
<li>Un carattere speciale tra "!,%,&,#,#,$,^,*,?,_,-"</li>
<li>Lunghezza minima: 8 caratteri</li>
</ul>
</div>
</fieldset>
</div>
<div class="securityCaptcha">
<p>Inserire il codice nei riquadri sottostanti</p>
<div class="first row">
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck last">
<canvas class="valiCaptcha"></canvas>
<button class="reloadButton">
<i class="fas fa-redo"></i>
</button>
</div>
</div>
<div class="second row">
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
</div>
</div>
<div class="contactArea">
<p>Compilare tutti i dati per la prenotazione.</p>
<input type="submit" name="submit" id="submit" value="send">
</div>
</div>
</form>
</div>
The BUTTON that create problem is the one with class reloadButton.
The INPUT is the one with id submit.
I think css aren't necessary.
Regarding the JS part:
let formEls = formPopup.querySelectorAll('.common, .message, .note');
let charCode = [];
const refreshButton = document.querySelectorAll('.reloadButton')[0];
const passInput = document.getElementById('password');
window.onload = function () {
document.querySelector('#reserveBtn').addEventListener('click', function () {
formPopup.classList.add('active');
});
getCode();
formPopup.querySelector('.closeButton').addEventListener('click', function () {
cleanForm();
formPopup.classList.remove('active');
});
formPopup.addEventListener('click', function (ev) {
if (ev.target.id == 'contactform-bg') {
cleanForm();
formPopup.classList.remove('active');
}
});
refreshButton.addEventListener('click', function (ev) {
charCode = [];
getCode();
});
passInput.addEventListener('keyup', function () {
passVal = passInput.value;
checkPass(passVal);
});
};
let cleanForm = function () {
formEls.forEach((item, i) => {
item.classList.remove('typing');
});
// console.log(window['contactform-bg'].innerHTML);
// console.log(document.getElementById('contactform').innerHTML);
// console.log(document.contactform.innerHTML);
document.contactform.name.value = '';
document.contactform.familyName.value = '';
document.contactform.email.value = '';
document.contactform.message.value = '';
passInput.value = '';
};
function getCode() {
let sChars = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,!,#,#,$,%,^,&,*,(,)';
let arrayChars = sChars.split(',');
for (var i = 0; i <= 3; i++) {
// trova un indice casuale tra 0 e la lunghezza dell'array
RefIndex = Math.floor(Math.random() * arrayChars.length);
// assegna il carattere estratto dall'array (strana indicazione del font come giapponese(??)
let char = arrayChars[RefIndex];
charCode[i] = char.toLowerCase;
createImgCaptcha(char, i);
}
}
I avoid to add the createImgCaptcha function because it just create CANVAS and doesn't have any impact on the matter.
Is there anyone able to explain to me why the FORM closes? I tried following the steps in JS but found no errors.
Thanks in advance.
Ok, I found the problems and fixed them.
There were little mistakes one different from another. So, I list them:
The "FORM close object": there was a missing '#' characer in the ref attribute, so I changed the HTML from to , adding also the type attribute for greater completeness.
The "class reloadButton": I finally read that a <button>Click to do something</button> is a default submit button. I didn't know... so, I just added the right type attribute to solve, in this way: <button class="reloadButton" type="button">.
The "submit button": in this case, I changed the prevent JS command: function stopEvent(event) { event.preventDefault();}.
Now, everything works correctly. Sorry if I bored you with these silly things; either way, it's always best to learn from mistakes.

How to change tag's inner html to the username?

I am trying to change (div.class=loguser)'s innerhtml to the username that has logged in. To get the username, I wrote a function that gets input of username and password from the register_button which is inside (div#register). I wrote an object(addData) which takes the username and password and stores it in an array(datas). After putting it in the array, I made a function where it verifies if the username and password exists in the array. If it does exist, it is suppose the change the innerhtml to the username. But it is not working. And I cant even submit the form while registering.
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(username, password) {
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
for (var i = 0; i < datas.length; i++) {
if (datas[i].username === username &&
datas[i].password === password) {
var name = username;
document.getElementsByClassName('loguser').innerHTML = username;
}
}
}
<body>
<div class="loguser">
<td>
<ul class="nav-area">
<li class="dropdown">User
</li>
</ul>
</td>
</div>
</tr>
</table>
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>
isUserValid() shouldn't take username and password as parameters, since it gets them from the inputs. It should take an event parameter, so you can call it as an event listener.
document.getElementsByClassName() returns a NodeList. You need to use [0] to access the first match to set its innerHTML. You could also use document.querySelector(), it just returns the first match.
The login button doesn't have an ID. Add id="login_button" so you can add an event listener to it.
Instead of your loop you can use the find() method to search an array.
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(e) {
e.preventDefault();
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
var found_user = datas.find(d => d.username === username && d.password === password);
if (found_user) {
document.getElementsByClassName('loguser')[0].innerHTML = found_user.username;
}
}
document.getElementById("login_button").addEventListener("click", isUserValid);
<body>
<div class="loguser">
User
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" id="login_button" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

Press Enter and the button function to be called

I have a page login, with label of user and pass. I want to know, how I do to when I press Enter in textbox to the button function to be called.
Login.js
$(document).ready(function () {
$("#btnOK").on("click", function () {
var UserName = $("#txt_user").val();
var Password = $("#txt_pass").val();
.
.
.
});
Login.cshtml
form action="#Url.Action("Default")" method="post">
<div id="boxLogin">
<br />
<label id="lbl_login">Login</label>
<div id="log">
<img src="../../img/images.jpg" alt=""/>
</div>
<div class="boxUser">
<label id="lbl_user">User: </label>
<input id="txt_user" type="text" value="" name="UserName">
</div>
<div class="boxPass">
<label id="lbl_pass">Pass: </label>
<input id="txt_pass" type="password" name="Password">
</div>
<div id="btns">
<input type="button" ID="btnOK" class="btn" value="Confirm" />
<input type="button" ID="btnCancel" class="btn" value="Cancel" />
</div>
</div>
</form>
You can submit it using below code:
$('#txt_usuario').on('keyup', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$( "#form" ).submit();
}
});
where form - is your form id.
$("#txt_senha").keyup(function(event){
if(event.keyCode == 13){
$("#btnOK").click();
}
});
Simple method is to change the btnOK element to a submit button (type="submit"), and change the javascript to run on the onsubmit event of the form.

field empty error for pop-up form

Can I have yout help pleas there,I make a validation field for a popup form :
function prepareEventHandlers() {
document.getElementById("contact").onsubmit = function () {
if (document.getElementById("message").value == '') {
document.getElementById("errorMessage").innerHTML = 'the field should not be empty!';
return false;
}
else {
document.getElementById("errorMessage").innerHTML = '';
return true;
}
};
}
window.onload = function () {
prepareEventHandlers();
}
then the html code :
<div id="form-content" class="modal hide fade in" style="display: none;">
<div class="modal-body">
<form class="contact" name="contact" >
<label class="label" for="message">Enter a Message</label><br>
<textarea id="message" name="message" class="input-xlarge"></textarea>
<p><span id="errorMessage"></span></p>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
No!
</div>
and I got this error :
TypeError: document.getElementById(...) is null document.getElementById("contact").onsubmit = function () {
Any Idea?
Edit:
OK I add id="contact" to my form so the error is gone but now the popup form is displyaed but when I try to click send with empty or not empty value nothing is happened...
just close </form> after <input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
and change html form id to contact

Categories

Resources