React onSubmit event not working - javascript

When I hit enter on the form, it does not trigger the onSubmit event. There are no errors. The other event, onBlur, does dispatch. The logForm function will eventually console.log a JSON string of all the form's fields, but I have not yet gotten that far. I am simply trying to trigger the onSubmit event on the form. Any help or explanation would be appreciated.
Here's the code:
import React from 'react'
export default function SignupForm() {
return (
<form onSubmit={logForm}>
<div className="form-group">
<label>
Name:
<input onBlur={logUpdate} className="form-control"
type="text" placeholder="Username"/>
</label>
</div>
<div className="form-group">
<label>
Email:
<input onBlur={logUpdate} className="form-control"
type="text" placeholder="johndoe#example.com"/>
</label>
</div>
<div className="form-group">
<label>
Password:
<input onBlur={logUpdate} className="form-control"
type="password" placeholder="Password"/>
</label>
</div>
<div className="form-group">
<label>
Confirm Password:
<input onBlur={logUpdate} className="form-control"
type="password" placeholder="Password"/>
</label>
</div>
</form>
)
}
function logForm(e) {
e.preventDefault()
const formInfo = new FormData(e.target)
console.log(formInfo)
}
function logUpdate(e) {
console.log(e.target.value)
}

What you can do is put an onKeyPressed event on your form controls like so
onKeyPress={this.onKeyPressed}
and then have a function catching the onKeyPressed
onKeyPressed: function (e) {
if (e.key === "Enter") {
logForm(e);
}
}
If you want Submit to work, add a button to your html section: (Credit to #TryingToImprove)
<div className="form-group">
<label>
<button className="btn btn-default" type="submit">submit form</button>
</label>
</div>

Related

onSubmit function is not invoked even after clicking on submit button

I am new to Reactjs. I just wrote this code and onSubmit function is not working. I am not getting if it's fault of register or form handleSubmit.Might be error in this line where the form tag is written.
Please guide and let me know of solutions.react-hook-form version is 7.14
React version is 17.02
FieldArray.js
import React, { Fragment } from "react";
import { useForm } from "react-hook-form";
function FieldArray() {
const { register, handleSubmit } = useForm();
const basicform = (
<div className="card">
<div className="card-header">Basic Information</div>
<div className="card-body">
<div>
<div className="form-group">
<label htmlFor="fullname">Full Name</label>
<input
type="text"
className="form-control"
id="fullname"
name="fullname"
{...register("fullname")}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input
type="email"
className="form-control"
id="email"
name="email"
{...register("email")}
/>
</div>
<div className="form-group">
<label htmlFor="phone">Phone Number</label>
<input
type="text"
className="form-control"
id="phone"
name="phone"
{...register("phone")}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
name="password"
{...register("password")}
/>
</div>
</div>
</div>
</div>
);
const onSubmit = data => {
console.log('hjhhhh');
console.log(data);
}
return (
<div className="App">
<div className="container py-5">
<form onSubmit={handleSubmit(onSubmit)}>{basicform}</form>
<button className="btn btn-primary" type="submit">Submit</button>
</div>
</div>
);
}
export default FieldArray;
We have to wrap the submit button inside the Form tag
<form onSubmit={handleSubmit(onSubmit)}>
{basicform}
<button className="btn btn-primary" type="submit">
Submit
</button>
</form>
Sandbox - https://codesandbox.io/s/silly-cori-t94eu?file=/src/react-hook-form.jsx

How can I resolve this React Modal Problem?

I am using react and I am a beginner in React. I am facing a problem while using React Modal.
It looks like modal is working but something is stopping it from working when I click on the button which opens Modal then this happens => The screen just blinks , The Modal opens and closes suddenly. I am using React useState Hook. No errors are reflected by the compiler in this code.
Here is my code :
import React from 'react'
import { useState } from 'react';
import Modal from 'react-modal'
import '../CSS/LoginSignup.css'
const LoginSignup = () => {
const [modalIsOpen , setIsOpen] = useState(false);
function openModal() {
setIsOpen(true);
}
function closeModal() {
setIsOpen(false);
}
function afterOpenModal() {
if(!closeModal){
setIsOpen(true);
}
}
return (
<>
<div>
<div className="mainContainer">
<div className="maincontrol">
<div className="tagline">
<h1>Chat Free</h1>
<span><p>Connect with peoples and chat the way you like.</p></span>
</div>
<div className="login">
<form className="form">
<input type="text" id="login" className="inp1" name="login" placeholder="Email address or phone number" />
<input id="password" type="password" className="inp1" name="login" placeholder="Password" />
<button type="submit" className="btn" value="Log In">Log In</button>
Forgotten password?
<button type="SignUp" className="btn1" value="Sign Up" name="signUp" onClick={openModal}>Sign Up</button>
<Modal isOpen={modalIsOpen}
onAfterOpen={afterOpenModal}
onRequestClose={closeModal}
>
<div className="modal">
<div className="modal-content">
<h2>Sign Up!</h2>
<span className="close" onClick={closeModal} >×</span>
<form className='formsignup'>
<div className="fullname">
<div className="firtname">
<input type="text" placeholder="First Name" id="firstname" />
</div>
<div className="surname">
<input type="text" placeholder="Last Name" id="lastname" />
</div>
</div>
<div className="emailphone">
<input type="text" placeholder="Email or phone number" id="ephone"/>
</div>
<div className="password">
<input type="password" placeholder="Enter password" id="password"/>
</div>
<div className="dobmain">
<div className="date">
<label htmlFor="dob">Date of birth</label>
<input type="number" placeholder="Date" id="date"/>
</div>
<div className="month">
<input type="text" placeholder="Month" id="month"/>
</div>
<div className="year">
<input type="number" placeholder="Year" id="year"/>
</div>
</div>
<div className="gender">
<div className="male">
<label htmlFor="">Male</label>
<input type="radio" name="gender" id="male" />
</div>
<div className="female">
<label htmlFor="">Female</label>
<input type="radio" name="gender" id="male" />
</div>
<div className="other">
<label htmlFor="">Other</label>
<input type="radio" name="gender" id="male" />
</div>
</div>
<div className="button">
<button type="Register" className="btnR" value="Register" name="register">Sign Up</button>
</div>
</form>
</div>
</div>
</Modal>
</form>
</div>
</div>
</div>
</div>
</>
)
}
export default LoginSignup
It is the content on my console:
[HMR] Waiting for update signal from WDS...
webpackHotDevClient.js:138 src\Component\LoginSignup.js
Line 33:33: The href attribute requires a valid value to be accessible. Provide a valid, navigable address as the href value. If you cannot provide a valid href, but still need the element to resemble a link, use a button and change it with appropriate styles. Learn more: https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-is-valid.md jsx-a11y/anchor-is-valid
printWarnings # webpackHotDevClient.js:138

Bootstrap form doesn't cancel submission when validation failed

I'm trying to create a form which will send an email to the user on submit.
The thing is that I used Bootstrap's form template and when I submit it with phone and mail wrong values (phone number even empty), the email is sent anyway (with 200 ok) and a success alert is showing.
Here is my HTML code:
<form class="needs-validation" novalidate id="paymentForm">
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First Name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="" value="" required>
<div class="invalid-feedback">
required Feild
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Lasr Name</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder="" value="" required>
<div class="invalid-feedback">
required Feild
</div>
</div>
</div>
<div class="mb-3">
<label for="email">Email</label>
<input type="email" class="form-control" value="" name="email" id="email" placeholder="you#example.com" required>
<div class="invalid-feedback">
please enter a valid mail address
</div>
</div>
<div class="mb-3">
<label for="phone">Phone Number</label>
<input type="tel" class="form-control" value="" name="phone" placeholder="example: 050-1111111" pattern="[0]{1}[5]{1}[0-9]{8}" id="phone" required>
<div class="invalid-feedback">
please provide a valid phone number
</div>
</div>
<div class="mb-3">
<label for="address"> address</label>
<input type="text" class="form-control" name="address" id="address" placeholder="" required>
<div class="invalid-feedback">
please provide your address
</div>
</div>
<hr class="mb-4">
<h4 class="mb-3">payment method</h4>
<div class="d-block my-3">
<div class="custom-control custom-radio">
<input id="cash" value="cash" value="cash" name="paymentMethod" type="radio" class="custom-control-input" required checked>
<label class="custom-control-label" for="cash">cash</label>
</div>
<div class="custom-control custom-radio">
<input id="bit" value="bit" value="bit" name="paymentMethod" type="radio" class="custom-control-input" required>
<label class="custom-control-label" for="bit">Bit</label>
</div>
</div>
<div class="invalid-feedback">
please choose method
</div>
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block" type="submit">continue to checkout</button>
</form>
and here is my js:
(function() {
'use strict'
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation')
Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
var radioValue = $('#paymentForm input:radio:checked').val()
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated')
var orderNumber = generateId();
var cName = $('#firstName').val() + " " + $('#lastName').val()
var cEmail = $('#email').val()
var cPhone = $('#phone').val()
var cAddress = $('#address').val()
var cSumToPay = parseInt(localStorage.getItem("totalPrice"));
var cProducts = JSON.parse(localStorage.getItem("products") || "[]");
cProducts = cProducts.map(Object.values);
cProducts = cProducts.join(' ');
console.log(cProducts);
var templateParams = {
order_number: orderNumber,
customer_name: cName,
products: cProducts,
addres: cAddress,
phone: cPhone,
customer: cEmail,
payment_Methode: radioValue,
customer_sum: cSumToPay
};
emailjs.send('gmail', 'orderconfirmation', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
alert('Yey! Your email was sent :)');
}, function(error) {
console.log('error');
alert(error);
});
event.preventDefault();
}, false)
})
}, false)
}())
I would be thankful if you guys can help me!!!
This section appears to be your only check for validation:
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
However, event.preventDefault() and event.stopPropagation() are not going to prevent the code from falling through to the next section. You can do that by including a return at this point
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
return false;
}
or you can wrap the rest of your code in the else of your conditional
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
// your email handling code
}
Note: your event.preventDefault() is useful to stop the submit button from performing its default behavior of submitting the form and event.stopPropagation() will just keep the event from bubbling up to parent elements (which you likely don't need). See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault and https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
In any case, you do not need two event.preventDefault() calls if you place a single one at the top of your event listener, e.g.
form.addEventListener('submit', function(event) {
event.preventDefault();
...

Javascript/Typescript - Prevent form from resetting on submit

I have a simple typescript class and a want to show the input results on submit. Even though this question is already asked, event.preventDefault() is not working. Maybe you can give me some hints?
class LoginPanel {
public appDiv: HTMLElement = document.getElementById('app');
constructor() {
this.setForm();
let btn = document.getElementById('loginButton');
btn.addEventListener('submit', (event) => {event.preventDefault(); this.submitForm()});
}
public setForm(): void {
this.appDiv.innerHTML = `<form id="loginForm" class="form-signin mt-5">
<div class="text-center">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
</div>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control mt-1" placeholder="Password" required="">
<button id="loginButton" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
`;
}
public submitForm(): void {
const elementFirst: HTMLElement = document.createElement('pre');
const elementSecond: HTMLElement = document.createElement('pre');
elementFirst.innerHTML = 'email: ' + document.getElementById('loginForm')[0].value;
document.getElementById('loginForm').appendChild(elementFirst);
elementSecond.innerHTML = 'password: ' + document.getElementById('loginForm')[1].value;
document.getElementById('loginForm').appendChild(elementSecond);
}
}
new LoginPanel();
When you submit a form, you submit all its values, not just one button.
Accordingly, the right place to prevent the default is within the form element itself, not its buttons.
constructor() {
this.setForm();
const form = document.getElementById('loginForm');
form.addEventListener('submit', (event) => {event.preventDefault(); this.submitForm()});
}
You can see that would work in this CodePen.
You can use onsubmit="return false" on the form instead:
<form id="loginForm" class="form-signin mt-5" onsubmit="return false">
<div class="text-center">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
</div>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control mt-1" placeholder="Password" required="">
<button id="loginButton" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
What's the difference?
The difference is that return false; takes things a bit further in that it also prevents that event from propagating (or "bubbling up") the DOM. The you-may-not-know-this bit is that whenever an event happens on an element, that event is triggered on every single parent element as well.
Alternatively, you could use event.stopPropagation on the form element:
constructor() {
this.setForm();
let btn = document.getElementById('loginButton');
btn.addEventListener('click', (event) => { this.submitForm()});
let form = document.getElementById('loginForm');
form.addEventListener('submit', (event) => { event.preventDefault(); event.stopPropagation; });
}
See: What's the difference between e.preventDefault(); and return false?

convert JQuery code to Pure Javascript

I'm trying to rewrite the following JQuery to Pure Javascript.
I don't know why the code isn't working, but it isn't working. I'm guessing I'm doing wrong with the use of "focusing". Would anybody help me please?
JQuery(working)
$('.form-group input').on('focus blur', function (e) {
$(this).parents('.form-group').toggleClass('active', (e.type === 'focus' || this.value.length > 0));
}).trigger('blur');
This is what I have so far(not working).
const inputs = document.querySelectorAll(".form-group input")
Array.from(inputs).forEach(input => {
input.addEventListener("focusin", (e) => {
const t = e.target as HTMLInputElement
let formgroup = t.parentElement
if(t.value.length > 0 ){
formgroup.classList.toggle("onblur")
}
})
})
Here is the html tag.
<form action="#" id="login-form">
<div class="form-group">
<label class="label-control">
<span class="label-text">Email</span>
</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label class="label-control">
<span class="label-text">Password</span>
</label>
<input type="password" name="password" class="form-control" />
</div>
<input type="submit" value="Login" class="btn" />
</form>
A couple of issues in regards to the jQuery code.
The class is named active and you are using onblur. The jquery code runs on both focus and blur.
const inputs = document.querySelectorAll(".form-group input");
const focusBlurHandler = (e) => {
const t = e.target;
let formgroup = t.parentElement;
if(t.value.length > 0 ){
formgroup.classList.toggle("active");
}
};
Array.from(inputs).forEach(input => {
input.addEventListener("focusin", focusBlurHandler);
input.addEventListener("focusout", focusBlurHandler);
});
.active{background:lightgreen}
<form action="#" id="login-form">
<div class="form-group">
<label class="label-control">
<span class="label-text">Email</span>
</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label class="label-control">
<span class="label-text">Password</span>
</label>
<input type="password" name="password" class="form-control" />
</div>
<input type="submit" value="Login" class="btn" />
</form>

Categories

Resources