My function doesn't display the alert (preventDefault) - javascript

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;

Related

How to stop Enter key press form submitting

I want to press enter key so that the form is not submitted, just click on the submit button and the form will be submitted in ReactJS
const handleSubmit = (data) ={
}
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" name="name" />
</label>
<input type="submit" value="Submit" />
</form>
You can change your handleSubmit function like this:
const handleSubmit = (e) => {
e.preventDefault()
}
e.preventDefault() this prevent the default behaviour of the form and all the events related to that.
What you can do is apply an onKeyPress handler to your form and if the value of the key that has been pressed is Enter, prevent the default behaviour (submit).
<form
onSubmit={handleSubmit}
onKeyPress={(e) => {
e.key === "Enter" && e.preventDefault();
}}
>
<label>
Name:
<input type="text" name="name" />
</label>
<button type="submit">Submit</button>
</form>
Note that you will likely also want to prevent the default for behaviour when your form is submitted, otherwise you'll likely get a page refresh.
const handleSubmit = (event) => {
event.preventDefault();
}
To get the value of your name input, you would do the following:
const handleSubmit = (event) => {
event.preventDefault();
console.log(event.target.name.value);
}
The same principle applies for any other fields you might have in the form.
Functioning CodeSandbox example.
You can do this without using a form tag and store the input values in a state
const handleSubmit = () ={
}
<div>
<div>
Name:
<input type="text" name="name" />
</div>
<input onClick={handleSubmit} value="Submit" />
</div>

Why function doesn't work with a button component but does with a button html tag in VUE js?

I made a VUE component button and tried to associate a v-on:click function, but it didn't work. Then I substituted it for an HTML button and it did work. I need to understand why.
I made this button component, which was loading ok on it's parent
<template>
<button v-on:click="action">{{ name }}</button>
</template>
<script>
export default {
name: "Appbutton",
data: function() {
return {};
},
props: {
name: String,
}
};
</script>
The code didn't fail when loaded by its parent:
<template>
<form class="login-form" action>
<label for="email">Register E-mail</label>
<input type="email" name="email" v-model="email" />
<label for="password">Register Password</label>
<input type="text" name="password" v-model="password" />
<div class="button-group">
<AppButton action="register" name="Login" />
<AppButton action="register" name="Login with Google" />
</div>
</form>
</template>
<script>
import AppButton from "#/components/AppButton";
export default {
name: "RegisterForm",
data() {
return {
email: "",
password: "",
show: true
};
},
methods: {
register: function(e) {
console.log("registered");
e.preventDefault();
}
},
components: {
AppButton
}
};
</script>
When pressed the "Login" button, it reloaded the page with the parameters email and password in the URL but the console.log was not displayed nor triggered anywhere. I tried sending the "register" function as a prop to the AppButton.vue but it had the same behaviour.
It only worked when I substituted the button component for a regular HTML button. Now it works as expected.
I just need to understand why is this behaviour, and how should I have to solve it?
Thanx in advance.
First of all you have to add action as a prop to your AppButton, then you need to bind your click event using :click="register".
I made a sandbox with an example: https://codesandbox.io/embed/vue-button-action-c5kun
Happens because of form submit is not prevented.
Put #submit.prevent on form tag
<form class="login-form" action #submit.prevent>
<label for="email">Register E-mail</label>
<input type="email" name="email" v-model="email" />
<label for="password">Register Password</label>
<input type="text" name="password" v-model="password" />
<div class="button-group">
<AppButton action="register" name="Login" />
<AppButton action="register" name="Login with Google" />
</div>
</form>

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

Using Javascript in HTML returning false even if the condition is true

I'm using Javascript in HTML to return a popup error if the input in the searchbar is not 'Dog'. However, it still shows the popup error when the input is 'Dog'.
<div class="search" >
<input type="text" name="s"
<a href="/redirect.php">
<button id="find" type="submit"
onclick="javascript: if(document.getElementById('find').value!='Dog')
{
alert('This animal does not exist in the system, try another one...');
return false;
}"> </button>
</div>
The code is supposed to go to redirect.php if the input in the searchbar is 'dog'. Where am I going wrong with the code?
try this
<div class="search" >
<input type="text" id="find" name="s" />
<a href="/redirect.php">
<button type="submit"
onclick="javascript: if(document.getElementById('find').value!='Dog') {
alert('This animal does not exist in the system, try another one...');
return false;
}"> </button>
</div>
Update:
The reason why it wasn't working before was because the button element had the find id instead of the text field.

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