Conflicting events: onKeyPress & onClick - javascript

I have a from like this:
With the following code:
<form onKeyPress={this.login.bind(this)}>
<input type="text" placeholder="username"/>
<input type="password" placeholder="password"/>
<button type="button" onClick={this.login.bind(this)}>Log In</button>
</form>
While I have the login() method like below:
login(e){
if((e.type==='keypress' && e.which===13) || e.type==='click'){
//Do login operations:
this.props.store.login()//the method inside MobX store
}
}
On following scenarios, there is no errors and I can login:
I click on the login button with mouse
I press Enter while the login button is NOT focused
But the following 3rd scenario, gives me errors due to the login operations being called twice:
When I press Enter while login button IS focused (for example login button is focused by pressing tab key)
I wonder what is the best practice by which I can avoid the errors of 3rd scenario. I looked through other related SO questions but I couldn't figure out the best practice.
I forgot to mention I'm using ReactJS with MobX.

Solved the problem by moving onKeyPress attribute from <form> tag to text-type <input> tags:
<form>
<input type="text" placeholder="username" onKeyPress={this.login.bind(this)}/>
<input type="password" placeholder="password" onKeyPress={this.login.bind(this)}/>
<button type="button" onClick={this.login.bind(this)}>Log In</button>
</form>

You could also use the onSubmit event if it suits your use case better:
Example (JS Bin)
class App extends Component {
login = (e) => {
e.preventDefault();
console.log('login');
}
render() {
return (
<form onSubmit={this.login}>
<input type="text" placeholder="username" />
<input type="password" placeholder="password" />
<button type="submit">Log In</button>
</form>
);
}
}

Related

My function doesn't display the alert (preventDefault)

I am working on a to-do list app (React.js) and trying to make use of the preventDefault function. I've added an onSubmit attribute to my form element and want it to display an alert when the add button is clicked. Problem is it doesn't seem to work, here's my code
function Form (props) {
function handleSubmit(e) {
e.preventDefault();
alert('Added')
}
return (
<form onSubmit={handleSubmit}>
<h2 className="label-wrapper">
<label htmlFor="new-todo-input" className="label-lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
className="input input-lg"
name="text"
autoComplete="off"
></input>
<button type="submit" className="btn btn-primary btn__lg">
Add
</button>
</form>
)
}
export default Form;

How to make sure a form is valid before submitting using JQuery?

I'm trying to make a login page and have the following:
<div id="loginField">
<input id="username" type="text" name="user" required></input>
<input id="password" type="password" name="password" required></input>
<input id="submit" type="submit" name="submit" value="Login"></input>
</div>
I made sure that the username and password fields are required. When the login is successful (for this sake, let's just say that both fields are not empty) a login disappears and another view appears. Anyway, I checked to see if the login button is pressed with JQuery:
$(function(){
$('#submit').on('click', function(){
$('#loginField').hide();
$('#differentView').show();});
The problem is that when the login button is clicked, the required attributes gets ignore and the next view is shown. How do I make sure that the required attributes are not ignored when the login button is clicked?
A crude way of doing it...
<div id="loginField">
<input id="username" type="text" name="user" class="required">
<input id="password" type="password" name="password" class="required">
<input id="submit" type="submit" name="submit" value="Login">
</div>
$('#submit').on('click', function(e){
e.preventDefault();
var isReady = true;
$('.required').each(function(){
if (this.value === '') {
isReady = false;
return;
};
});
if (isReady) {
// submit form
};
});
You can use this library: Parsley. It is a javascript form validation library and it is very easy to use and you can customize it for your own means. Good luck!
Instead of handling onclick on button, you can put input fields into the form...
<form action="post" method="post" id="loginField">
<input id="username" type="text" name="user" required></input>
<input id="password" type="password" name="password" required></input>
<input id="submit" type="submit" name="submit" value="Login"></input>
</form>
... and in jQuery you can handle on submit action like this:
$(document).ready(function(){
$('#loginField').on('submit', function(event){
event.preventDefault();
var [username password] = $(this).serializeArray(),
username = username.value,
password = password.value;
/* some validations */
});
});
event.PreventDefault prevents browser from subbmiting so your page won't be refresh. serializeArray returns an array of objects (key-value) that's why you have to use .value
The required attributes are ignored because the input elements are not inside an html form element
To use the HTML5 input valuation attributes (required, minlength... etc)
The inputs should be grouped inside a form element, and you can listen for the form submit event, that is triggered by default when the user press enter (while focus is on a field inside the form) or clicks the submit button (input or button with type="submit") that is also wrapped inside the form
HTML
<form id="loginForm">
<input id="username" type="text" name="user" required />
<input id="password" type="password" name="password" required />
<input id="submit" type="submit" name="submit" value="Login" />
</form>
Javascript
$(function(){
$('#loginForm').on('submit', function (event) {
event.preventDefault(); // prevent default form submit page reload
console.log('I will enter this handler only on valid form')
$('#loginForm').hide();
$('#differentView').show();
})();
Here is a basic plunker with 2 examples https://plnkr.co/edit/I0vUMSeOlrjlYYu4VofU?p=preview
using the default html5 validation
using Parsley

How can I create the same functionality of onsubmit="return groupAdd()" when dynamically adding the onsubmit with an EventHandler?

Use to just add an onclick event with a button and collect data, did not even need a form element, but with HTML5 you can take advantage of error check and default messages displayed when a user submits a form.
<input type="email" id="addEmail" name="addEmail" placeholder="user#sample.com" value="" required="" title="" />
Since the type is email and there is a require attribute present the browser will check for a well structured email address onsubmit. If the value fails a message appears under the input indicating the user must fix the value.
You can also use regular expression for example
<input type="password" id="addPassword" name="addPassword" placeholder="Password" value="" required="" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$" title="" />
All together you have
<script>
function userAdd(){
*** xmlhttprequest code *******
return false;
}
</script>
<html>
<form action="admin" method="post" onsubmit="return userAdd();">
<input type="email" id="addEmail" name="addEmail" placeholder="user#sample.com" value="" required="" title="" />
<input type="password" id="addPassword" name="addPassword" placeholder="Password" value="" required="" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$" title="" />
<input type="submit" value="Submit" />
</form>
</html>
When I generate the form element dynamically I need to attach an event handler:
f = document.createElement('form');
addEventHandler(f,'submit', function(){userAdd()});
function addEventHandler(elem,eventType,handler) {
if (elem.addEventListener)
elem.addEventListener (eventType,handler,false);
else if (elem.attachEvent)
elem.attachEvent ('on'+eventType,handler);
}
}
The reason I want to keep the default submit functionality is because of the built in HTML5 features.
How can I create the same functionality of onsubmit="return groupAdd()" when dynamically adding the unsubmit with an EventHandler?
For HTML5 with DOM2 API:
f.addEventListener('submit', function(e) { if (!userAdd()) {
e.preventDefault(); } });

Multiple Forms with one login

So I want to have one login, but I have 2 different forms to distinguish different functions. How do I pass the login forms between the other 2 functions.
I know javascript and vbs, not jquery.
Example:
I want the same user and pass to appy to both forms without having to make 2 seperate inputs
<%
username = Request.Form("username")
password = Request.Form("password")
%>
<input name="username" />
<input name="password" type="password" />
<form action="test.asp?f=test1" method="post">
text inputs with a submit button
</form>
<form action="test.asp?f=test2" method="post">
different inputs with another submit button
</form>
I haven't used ASP Classic for ages so I am not sure if this is a correct answer, but you can give it try. Since you have two buttons and you want to know which button is being clicked. Why don't you give value to each submit button and then give it the same name? For example.
<form action="test.asp" method="post">
<input name="username" />
<input name="password" type="password" />
<input name='action' type="button" value="Submit One" />
<input name='action' type="button" value="Submit Two" />
</form>
The ASP part
If Request.Form("action") = "Submit One" Then
'' First button is clicked
Else
'' Second button is clicked
End If
I think you're possibly over-thinking this.
I'd put the username and password inputs into a single form and have both submit buttons displayed as follows:
<form action="test.asp?f=test1" method="post">
<input name="username" />
<input name="password" type="password" />
<input id="submit-1" type="button" value="Submit One" />
<input id="submit-2" type="button" value="Submit Two" />
</form>
Then, using JavaScript I'd wire up click event handlers on each button such that when the user click either one, the form action URL querystring would be updated before submitting the form.
var button1 = document.getElementById("submit-1");
var button2 = document.getElementById("submit-2");
b1.onclick = function() {
document.form.action = "test.asp?f=test1";
document.form.submit();
}
b2.onclick = function() {
document.form.action = "test.asp?f=test2";
document.form.submit();
}

change active state on div's by clicking a link

I'm currently having some issues with a Login-box. I'm using my own version with the logic behind a tutorial online. It all works fine right now. When I click my Login button, a JQuery trigger displays the window which has the class active assigned to it. And once the login box has appears, the user could click on register in the login box and a register window becomes active. I know i could be a bit hard to follow here but the question should be fairly easy. I want to press a new button next to LOGIN, that takes the user directly to REGISTER. For that I would need to set the active state to different forms depending on which button I press. I'm trying to make a js script that senses which link has been click and then sets the active state to that form. So the first Code is the links, right now both of them open the login box at the signin stage. But my goal is to get the second one to open the register stage. Is this possible? How can I set the active state to the right form in a click ?
Here is an jsFiddle
HTML
<li>Login</li>
<li>Register</li>
<div id="login-box" class="login-popup"></div>
<form class="register" >
<input type="text" name="login" placeholder="email">
<input type="password" name='password' placeholder="pass" required>
<input type="submit" name="submit" value="Reg">
login
</form>
<form class="signin active">
<input type="text" name="login" placeholder="email">
<input type="password" name='password' placeholder="pass" required>
<input type="submit" name="submit" value="Login">
Reg
</form>
Javascript
$(function() {
//the form wrapper (includes all forms)
var $form_wrapper = $('#login-box'),
//the current form is the one with class active
$currentForm = $form_wrapper.children('form.active'),
//the change form links
$linkform = $form_wrapper.find('.linkform');
$linkform.bind('click', function(e) {
var $link = $(this);
var target = $link.attr('rel');
$currentForm.fadeOut(400, function() {
//remove class active from current form
$currentForm.removeClass('active');
//new current form
$currentForm = $form_wrapper.children('form.' + target);
//animate the wrapper
$form_wrapper.stop()
.animate({
height: $currentForm.data('height') + 'px'
}, 500, function() {
//new form gets class active
$currentForm.addClass('active');
//show the new form
$currentForm.fadeIn(400);
});
});
e.preventDefault();
});
});
I re-read your question, I think I hear where you are having problems:
// NOTE: add id="signinForm" and id="registerForm" to your forms, I suggest this over class="signin" and class="register" as you'll only have one signin/register form throughout your app.
// rename rel="register" to id="register", why are you using rel? http://www.w3schools.com/TAGS/att_a_rel.asp
$("#signin").click(function() {
$("#registerForm").removeClass("active");
$("#signinForm").addClass("active");
});
$("#register").click(function() {
$("#signinForm").removeClass("active");
$("#registerForm").addClass("active");
});
To access and submit your form, create another click event to your submit buttons:
$("input[type=submit]").click(function() {
var form = $("form.active")[0];
form.submit();
});
why don't you use tabs?
<div id="tabs">
<ul>
<li>Login</li>
<li>Register</li>
</ul>
<div id="tabs-1">
<form class="login" >
<input type="text" name="login" placeholder="email">
<input type="password" name='password' placeholder="pass" required>
<input type="submit" name="submit" value="Reg">
login
</form>
</div>
<div id="tabs-2">
<form class="register">
<input type="text" name="login" placeholder="email">
<input type="password" name='password' placeholder="pass" required>
<input type="submit" name="submit" value="Login">
Reg
</form>
</div>
</div>
JS:
$(function() {
$( "#tabs" ).tabs();
});
it should be pretty much easier and you get the desired behaviour.
Greetings,

Categories

Resources