How to stop Enter key press form submitting - javascript

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>

Related

In react deselect the radio button after all the input fields have been processed

I am creating a form in react, where the user enters into the input text fields: name, role and selects the gender by the radio button. On clicking the submit button the user stores the entered data into a state. The values are displayed below the form. What I want is, every time the submit button is pressed, the new values added gets displayed, as well as all of the fields get empty as well. I know how to reset the input text fields but am not able to reset the radio buttons. Any Idea how can I reset the radio buttons as well.
The code is :
const [user, setUser] = useState({}); // state is created
the form body is :
<div className="entryForm">
<span>
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
value={user?.name}
onChange={(e) =>
setUser((prev) => ({
...prev,
name: e.target.value,
}))
}
></input>
</span>
<span>
<label htmlFor="role">Role</label>
<input
type="text"
id="role"
value={user?.role}
onChange={(e) =>
setUser((prev) => ({
...prev,
role: e.target.value,
}))
}
></input>
</span>
<h3>Gender</h3>
<div className="radio">
<span>
<input
type="radio"
id="male"
value="male"
name="gender"
onChange={(e) =>
setUser((prev) => ({
...prev,
gender: e.target.value,
}))
}
></input>
<label htmlFor="male">Male</label>
</span>
<span>
<input
type="radio"
id="female"
value="female"
name="gender"
onChange={(e) =>
setUser((prev) => ({
...prev,
gender: e.target.value,
}))
}
></input>
<label htmlFor="female">Female</label>
</span>
</div>
<button
onClick={() => {
dispatch(addUser(user)); // to send data to other component
setUser({
name: "",
role: "",
gender: "",
});
}}
>
Submit
</button>
</div>
Input type="radio" has attribute name checked, you can toggle it with true/false value.
From what I understand from your code, your input should look something like this
<input
type="radio"
name="gender"
value="female"
checked={(user?.gender == 'female')} //which will be true if female was choosen
/>
and then when you complete sending the data you can set user.gender = false
This is a perfect example of where you can use features of native html to help you achieve your goal. On top of that, you should almost always wrap any form in an actual <form> tag.
In your case, it should be as easy as changing your div to a form:
<form className="entryForm">
...
</form>
Then you can call form.reset() on the form, which will revert the form to its initial state. You will need a ref to the form in order to do this:
const formRef = useRef();
<form ref={formRef} className="entryForm">
...
<button
type="submit"
onClick={() => {
...
formRef.current.reset();
}}>
Submit
</button>
NOTE: if you add type="submit" to your button, and the button is inside a <form/>, then users can submit the form by hitting ENTER - which is good for usability.
Here's a full example: https://playcode.io/985741
set the value value="male" of your radio buttons by using useState and set the state empty when the button is pressed or when the data is send

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;

Required Attribute wont work on with addEventListener?

My goal is that passing data from a form to another element.
My code works when passing the data, but the time when the form is empty and user attempt to press the button, the required attribute won't work even tho I put the attribute to every form inputs. I want to prevent user submitting empty data.
Here's a sample code
const passBtn = document.querySelector("#btnSubmit");
const inputEmail = document.querySelector("#inputEmail");
const recieveText = document.querySelector("#recieveText");
const getEmail = document.querySelector("#getEmail");
passBtn.addEventListener("click", function(e) {
e.preventDefault();
getEmail.textContent = inputEmail.value;
})
<form legend="Form">
<fieldset>
<legend>
MyForm
</legend>
<input id="inputEmail" type="email" placeholder="Email" required />
<button id="btnSubmit" type="submit">
Pass Text
</button>
</fieldset>
</form>
<div id="wrapper">
<p>
Recieved Text Here
</p>
<div class="content-wrapper">
<span id="getEmail"> </span>
</div>
</div>
for having the form validation triggered you need to listen to the form submit event and for that you can change your code to:
const form = document.querySelector("#form");
const inputEmail = document.querySelector("#inputEmail");
const recieveText = document.querySelector("#recieveText");
const getEmail = document.querySelector("#getEmail");
form.addEventListener("submit",function(e){
e.preventDefault();
getEmail.textContent = inputEmail.value;
/* recieveText.value = inputEmail.value; */
})
and also you need to have a name attribute for elements as well:
then update:
<input id="inputEmail" type="email" placeholder="Email" required />
to
<input id="inputEmail" type="email" name="inputEmail" placeholder="Email" required />
https://jsfiddle.net/ko5py9cw/

How to pass text from inputtext to URL?

I want to pass text of input, id = "u_name" to the form action url.
<form id = "ismForm" action = {% url 'polls:todo' %} method="get" >
<input type="text" id = "u_name" name="name" />
<input type="text" name="email" />
<input type="text" name="pass" />
{% csrf_token%}
<input type="submit" name="click" value="Register" />
/>
</form>
Add a listener on the form for submit. On submit add the u_name value to the action.
const form = document.getElementById("ismForm");
form.addEventListener("submit", function(e){
//check to see if the form is valid before doing this...
this.action += `?u_name=${form.querySelector('#u_name').value}`
})
No need to do e.preventDefault() as the goal is to let the form submit be handled by the navigator.
Working example: ( e.preventDefault() is required to see console.log output)
const form = document.getElementById("ismForm");
form.addEventListener("submit", function(e){
e.preventDefault()
this.action += `?u_name=${form.querySelector('#u_name').value}`
console.log(this.action);
})
<form id = "ismForm" action ="/some/url" method="get" >
<input type="text" id = "u_name" name="name" />
<input type="submit" name="click" value="Register" />
</form>

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