Login using enter key - javascript

I have login form in my app. Currrently I have a Login button to login. When this login button is clicked, I send the username and password values to the backend api which in turn generates a token and allow the user to move to next screen if authenticated. I want the same functionality when I press enter key. I have looked to many sources but I need a secure way. How can I do it. This is my form component
render(){
return (
<div className="LoginPage">
<div className="login-page">
<div className="form">
<form className="login-form">
<input id="username" type="username" placeholder="username"/>
<input id="password" type="password" placeholder="password"/>
<p className="message">Not registered? Request Username and Password</p>
</form>
<button onClick={this.handleLoginButtonClick.bind(this)}>login</button>
</div>
</div>
</div>
);
}

Use the onKeyDown event with input fields, and in this method check the keycode of the key pressed by the user, Key code of Enter key is 13, so whenever he pressed enter, call the same method that you are calling on button click, Write it like this:
render(){
return (
<div className="LoginPage">
<div className="login-page">
<div className="form">
<form className="login-form">
<input id="username" type="username" placeholder="username" onKeyDown={this.onKeyDown.bind(this)}/>
<input id="password" type="password" placeholder="password" onKeyDown={this.onKeyDown.bind(this)}/>
<p className="message">Not registered? Request Username and Password</p>
</form>
<button onClick={this.handleLoginButtonClick.bind(this)}>login</button>
</div>
</div>
</div>
);
}
onKeyDown(e){
if(e.keyCode == 13){
/*write the logic here*/
}
}
You need to use ref to focus the field if user left them blank.
Check jsfiddle for working example with focusing the field: https://jsfiddle.net/ygytaj6s/

Related

Angular form is undefined when submitting via ngSubmit

I have a form outlined in my app.component.html file as below, when I click the Send button to submit the form I get an error in my Javascript saying that the chatForm is undefined.
I've had a look at a few different tutorials and I can't seem to find why this function is not operating as I expect. What am I doing wrong?
Also when I'm submitting the form how do I get the value of the input that is present in my form? I have a name of message defined on the form, how can I use this variable?
app.component.html
<div class="container">
<h2>Message Form</h2>
<form (ngSubmit)="sendMessage(chatForm)" #chatForm="ngForm">
<div>
<label for="message">Message</label>
<input type="text" id="message" name="message" [(ngModel)]="message" required>
</div>
<button type="submit" id="sendmessage" [disabled]="!chatForm.valid">
Send
</button>
</form>
</div>
app.component.ts
public sendMessage(form): void {
console.log("Message sent: " + form.value);
}
You should get the data by using
form.value.message
My example look like this
<form (ngSubmit)="onSubmit(registerForm)" #registerForm="ngForm">
<div class="form-group">
<label for="UserName">Your email</label>
<input
type="text"
ngModel
class="form-control"
id="UserName"
name="UserName"
required
/>
Then in my component I can access to the form data like this
onSubmit(formValue: NgForm) {
const registerModel: AccountModel = {
UserName: formValue.value.UserName,
Password: formValue.value.Password
};

Simple use of the 'required' attribute but also validate the form (to exclude '#')

I’m trying to create a form that ensures the name input field excludes the ‘#‘ symbol but also has the same box appear prompting the user to fill in the field if empty. I assume the box may differ per browser.
To explain my demo further, see this default form:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button type="submit" value="Subscribe">submit</button> <!-- WITH input type submit -->
</div>
</form>
Clicking the submit button will only submit if all fields are completed, but it won’t check if the name field includes an ‘#‘. I can’t edit it to only submit if the field doesn’t include an ‘#‘.
But this demo:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button onclick="checkName()" type="button" value="Subscribe">submit</button> <!-- changed from input type submit -->
</div>
<script>
let form = document.getElementById('form-id'),
ecsName = document.getElementById('name-id'),
ecsEmail = document.getElementById('email-id'),
ecsCheckbox = document.getElementById('checkbox-id');
function checkName() {
let name = ecsName.value,
email = ecsEmail.value;
if(name.includes('#')) {
alert('includes #');
} else if (name == '' || email == '') {
alert('please fill in your details');
} else if (ecsCheckbox.checked == false) {
alert ('unckeded');
} else {
form.submit();
}
}
</script>
</form>
Includes javascript that ensures all fields are completed, but I don’t like the alert and want the same prompt box to appear as with the former form.
Is there any way of doing this? I’m essentially trying to not tamper with the form and let the default settings do most of the work if possible. Also, another quick question - should required be required='required'? Thanks for any help here.

Clear url after submit

I'm using react, redux and react-router in my application. When I submit login and password I post axios request to my backend and then update my user after I get a response. This works fine, but my problem is that after i press Enter or click "Login" my url change to something like this:
http://localhost:3000/?email=example123%40gmail.com&password=pass123
Is there any way to prevent url from changing or to clear it after submit?
Form:
<form onSubmit={this.login}>
<div className="loginForm">
<label> Email</label>
<input type="text" name="email" onChange={this.handleChange} />
<div className="loginError">{this.state.emailErr}</div>
<label>Password</label>
<input type="password" name="password" onChange={this.handleChange} />
<div className="loginError">{this.state.pswdErr}</div>
<span style={{paddingTop: "30px"}}/>
<button style={{width: "100%"}} type="submit" >Login </button>
</div>
</form>
Your form is trying to submit itself by default.
Add this to your login method:
login(event) {
event.preventDefault();
}

how do i use an an enter key stroke to submit a username and password

I have a login button that works fine,it logs a user in etc.. but i want to allow the user to press the enter key to login as well. how do i do this.I tried a test using onkeypress but it didnt do anything as bellow
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username id="username" />
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="........" id="password" onkeypress=myFunction() /> //i just tried this myFunction() to see if it would give an alert but it doesnt
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-login" id="btnLogin">Log in</button>
</div>
</div>
</form>
function myFunction()
{ alert("button pressed")}
so how do i use the enter key to submit my request in javascript and jquery
As you've placed the input within a form element which contains a submit button, you get this behaviour by default. To hook to it, use the submit event of the form, like this:
$('form').on('submit', function(e) {
e.preventDefault(); // only used to stop the form submission in this example
console.log('form submitted');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" id=" username" />
</div>
<div class="form-group ">
<input type="password" class="form-control" placeholder="........" id="password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-login" id="btnLogin">Log in</button>
</div>
</form>
Note that I fixed the missing " after the placeholder attribute in the first input. You also don't need the trailing space after all the attribute values, so I removed those too.
First you need to send the Event to the myFunction() function and add ID to your form to add submit manually::
HTML
<form id='myForm'>
<!-- form actions (etc..) -->
<input type="password" class="form-control" placeholder="........" id="password" onkeypress=myFunction(e) />
<!-- form actions (etc..) -->
</form>
Now in ASCII the reenter code is 13 all you need to check is when the pressed key is reenter (13) then you need to take the event key code and call the submit function::
function myFunction(e)
var code = (e.keyCode ? e.keyCode : e.which);
{
if (code == "13")
{
//Calling the submit or clicking manually it
$( "#myForm" ).submit();
}
}

Conflicting events: onKeyPress & onClick

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>
);
}
}

Categories

Resources