Press Enter and the button function to be called - javascript

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.

Related

Incorrect & Correct statement

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>

My Javascript if statement returns true even though it is false

I have a button and a form on my page. When the button is clicked it should display the form, and when click again it should hide the form.
For some reason, whenever the button is clicked it executes the first if statement regardless of whether it is true or not. How can I fix this?
Here is my HTML code
<div class="return-user-signin">
<h2 class="checkout-return-cust">Returning customer?</h2>
<button class="checkout-login-button"><i class="fas fa-user"></i> log in</button>
<form class="woocomerce-form woocommerce-form-login login check-login pop-login-form" method="post" style="display: none;">
<p class="form-row form-row-first">
<input placeholder="Username or email" class="input-text placeholder" name="username" id="username" type="text">
</p>
<p class="form-row form-row-last">
<input class="input-text placeholder" placeholder="Password" name="password" id="password" type="password">
</p>
<div class="clear"></div>
<p class="form-row">
</p>
<div class="clear"></div>
</form>
Here is my JavaScript
var login_button = $(".checkout-login-button");
var login_form = $(".pop-login-form");
if (login_form.css('display') == "none") {
$(document).on('click', '.checkout-login-button', function () {
login_form.show();
login_form.off('click');
login_form.css('display', 'block');
return;
});
} else {
$(document).on('click', '.checkout-login-button', function () {
login_form.hide();
login_form.off('click');
login_form.css('display', 'none');
return;
});
}
You have first to create the event, then inside it you do your conditional statements.
var login_button = $(".checkout-login-button");
var login_form = $(".pop-login-form");
$(document).on('click', '.checkout-login-button', function(){
if( login_form.css('display') == "none" ) {
login_form.show();
login_form.off('click');
login_form.css('display', 'block');
return;
} else {
login_form.hide();
login_form.off('click');
login_form.css('display', 'none');
return;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="return-user-signin">
<h2 class="checkout-return-cust">Returning customer?</h2>
<button class="checkout-login-button"><i class="fas fa-user"></i> log in</button>
<form class="woocomerce-form woocommerce-form-login login check-login pop-login-form" method="post" style="display: none;">
<p class="form-row form-row-first">
<input placeholder="Username or email" class="input-text placeholder" name="username" id="username" type="text">
</p>
<p class="form-row form-row-last">
<input class="input-text placeholder" placeholder="Password" name="password" id="password" type="password">
</p>
<div class="clear"></div>
<p class="form-row">
</p>
<div class="clear"></div>
You can have only one click handler and check the CSS state inside it. Besides, css is taking care of the visibility using display:block/none, so in my opinion the show()/hide() methods are redundant.
var login_button = $(".checkout-login-button");
var login_form = $(".pop-login-form");
$(document).on('click', '.checkout-login-button', function() {
if (login_form.css('display') === "none") {
login_form.css('display', 'block');
} else {
login_form.css('display', 'none');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="return-user-signin">
<h2 class="checkout-return-cust">Returning customer?</h2>
<button class="checkout-login-button"><i class="fas fa-user"></i> log in</button>
<form class="woocomerce-form woocommerce-form-login login check-login pop-login-form" method="post" style="display: none;">
<p class="form-row form-row-first">
<input placeholder="Username or email" class="input-text placeholder" name="username" id="username" type="text">
</p>
<p class="form-row form-row-last">
<input class="input-text placeholder" placeholder="Password" name="password" id="password" type="password">
</p>
<div class="clear"></div>
<p class="form-row">
</p>
<div class="clear"></div>
</form>
Change your JavaScript as below:
var login_button = $(".checkout-login-button");
var login_form = $(".pop-login-form");
var show_form = false; // add this line
$(document).on('click', '.checkout-login-button', function () {
if(!show_form){
//SHOW FORM
show_form = true;
}else{
//HIDE FORM
show_form = false;
}
});
You seem to be trying to change the function handling the click, which would be accomplished by removing the existing one and adding another. You’re trying to remove it here:
login_form.off('click');
but that doesn’t work when you actually added the listener to document to make use of event delegation, and no listener is being added again after this.
It’s simpler to just have one listener, and to attach it directly to the element if it exists at the time:
var login_form = $(".pop-login-form");
$(".checkout-login-button").click(function () {
login_form.toggle();
});
which your login_button initialization suggests is the case. If not, continue with event delegation by all means:
var login_form = $(".pop-login-form");
$(document).on("click", ".checkout-login-button", function () {
login_form.toggle();
});
It's the other way around, you define the .click() event once and inside it you define the logic for the if-else structure.
The way you have it now, it is only showing the form (never hiding it) because the only part of the code being run is the one inside login_form.css('display') == "none" which is true when the page loads
HIH
var login_button = $(".checkout-login-button"); var login_form = $(".pop-login-form");
$(document).on('click', '.checkout-login-button', function(){
if( login_form.css('display') == "none" ) {
login_form.show();
login_form.off('click');
login_form.css('display', 'block');
}
else {
login_form.hide();
login_form.off('click');
login_form.css('display', 'none');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="return-user-signin">
<h2 class="checkout-return-cust">Returning customer?</h2>
<button class="checkout-login-button"><i class="fas fa-user"></i> log in</button>
<form class="woocomerce-form woocommerce-form-login login check-login pop-login-form" method="post" style="display: none;">
<p class="form-row form-row-first">
<input placeholder="Username or email" class="input-text placeholder" name="username" id="username" type="text">
</p>
<p class="form-row form-row-last">
<input class="input-text placeholder" placeholder="Password" name="password" id="password" type="password">
</p>
<div class="clear"></div>
<p class="form-row">
</p>
<div class="clear"></div>

Onsubmit in form does not called

I have next form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function submit(form) {
var first_pass = form.find('.first_try');
var second_pass = form.find('.second_try');
if (first_pass.value == second_pass.value) {
return true
}
first_pass.value = '';
second_pass.value = '';
first_pass.attr('placeholder', 'Пароли не совпадают');
first_pass.css('border-color', 'red');
second_pass.css('border-color', 'red');
return false
}
</script>
<form role="form" method="post" onsubmit="return submit($('#PasswordChange form'))">
<h3>Редактирование пользователя</h3>
<div class="form-group">
<input type="password" class="form-control first_try" name="password"
placeholder="Новый пароль"
required>
</div>
<div class="form-group">
<input type="password" class="form-control second_try" name="password"
placeholder="Повтор пароля"
required>
</div>
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить"></input>
</form>
This script checks whether passwords are the same.
But using firefox debugger i can't find that it goes into this method.
Is this problem with script? Or Is ths problem about declaring onsubmit handler?
There was many problems:
change value to val
use another name for submit function, it's kinda reserved
use this instead of $('#PasswordChange form')
use var first_pass = $('.first_try'); instead of find
you forgot to write else
and you need use event.preventDefault(); to stop refreshing page or submiting page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function save(form) {
var first_pass = form.querySelector('.first_try');
var second_pass = form.querySelector('.second_try');
if (first_pass.value == second_pass.value) {
alert('its ok');
return true;
} else {
first_pass.value = '';
second_pass.value = '';
first_pass.placeholder = 'Пароли не совпадают';
first_pass.style.borderColor='red';
second_pass.style.borderColor='red';
return false
}
}
</script>
<form role="form" method="post" onsubmit="event.preventDefault(); return save(this)">
<h3>Редактирование пользователя</h3>
<div class="form-group">
<input type="password" class="form-control first_try" name="password"
placeholder="Новый пароль"
required>
</div>
<div class="form-group">
<input type="password" class="form-control second_try" name="password"
placeholder="Повтор пароля"
required>
</div>
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить"/>
</form>
Use this code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function submitData(form) {
var first_pass = form.find('.first_try');
var second_pass = form.find('.second_try');
if (first_pass.value == second_pass.value) {
return true
}
first_pass.value = '';
second_pass.value = '';
first_pass.attr('placeholder', 'Пароли не совпадают');
first_pass.css('border-color', 'red');
second_pass.css('border-color', 'red');
return false
}
</script>
</head>
<body>
<form role="form" method="post" onsubmit="return submitData($('#PasswordChange form'))">
<h3>Редактирование пользователя</h3>
<div class="form-group"> <input type="password" class="form-control first_try" name="password" placeholder="Новый пароль" required></div>
<div class="form-group"> <input type="password" class="form-control second_try" name="password" placeholder="Повтор пароля" required></div><input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить"></form>
</body>
</html>
Please change submit function name because it is keyword so it is not use it. Also remove </input> next to submit button
Use this :
onsubmit="return submit(this)"
You should not return anything if you don't need to cancel the submit action. Also you could use submit form event handler with jQuery .submit() method instead of hanler definition in onsubmit attribute.
$("form").submit(function(e) {
var passwords = $('[name=password]');
if (passwords.eq(0).val() !== passwords.eq(1).val()) {
alert("Пароли не совпадают!");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" method="post" action="/">
<h3>Редактирование пользователя</h3>
<div class="form-group">
<input type="password" class="form-control first_try" name="password" placeholder="Новый пароль" required >
</div>
<div class="form-group">
<input type="password" class="form-control second_try" name="password" placeholder="Повтор пароля" required />
</div>
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить" />
</form>
Also I recommend you to use Bootstrap validation states instead of input's border style setting.

blur function not being first

I am using regex to disable registering with a apple email
if (str.match('(#me.com)') || str.match('(#icloud.com)') || str.match('(#mac.com)'))
The code is working fine if I run it with the browser console but I cant get it to work initially, Ive wrapped it in a $(document).ready(function () { .. } as well the blur function just never seems to fire. Here is the code below as well as CodePen
Html
<div class="content">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" role="form">
<div class="warning email-warning" style="display:none;">A non-Apple email address is required due to issues with our mail server. Sorry about that!</div>
<input type="text" name="email" placeholder="" value="" id="Email"/>
<input type="password" name="password" placeholder="Password" value="" />
<input style="font-size: 1.5rem;" type="submit" value="Login" class="btn btn-default" />
<div class="already">Don't have an account? Register</div>
<a class="block text-center" href="/index.php?route=account/forgotten">Forgot your password?</a>
</form>
</div>
JS
function emailValidate(){
var str = $('#Email').val();
$('#Email').blur(function() {
if (str.match('(#me.com)') || str.match('(#icloud.com)') || str.match('(#mac.com)')) {
$('.email-warning').css('display', 'block')
}
});
}
emailValidate()
You need to re-assign the value using val() to variable str inside blur event callback.
function emailValidate(){
$('#Email').blur(function() {
var str = $(this).val();
if (str.match('(#me.com)') || str.match('(#icloud.com)') || str.match('(#mac.com)')) {
$('.email-warning').css('display', 'block')
}
alert(str)
});
}
emailValidate()
you must get value of target object #Email when the blur event trigger. In your code, you get that value when you bind blur event.
Try with
function emailValidate(){
$('#Email').blur(function() {
var str = $('#Email').val();
if (str.match('(#me.com)') || str.match('(#icloud.com)') || str.match('(#mac.com)')) {
$('.email-warning').css('display', 'block')
}
});
}
emailValidate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<form role="form">
<div class="warning email-warning" style="display:none;">A non-Apple email address is required due to issues with our mail server. Sorry about that!</div>
<input type="text" name="email" placeholder="" value="" id="Email"/>
<input type="password" name="password" placeholder="Password" value="" />
<input style="font-size: 1.5rem;" type="submit" value="Login" class="btn btn-default" />
<div class="already">Don't have an account? Register</div>
<a class="block text-center" href="/index.php?route=account/forgotten">Forgot your password?</a>
</form>
</div>
Hope this helps.
Regards.

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