Manually trigger HTML validation on button click - javascript

I am trying to handle form validation on button click. It is validating the form but not showing error.
can anyone help me in this?
<form id="the-form" action="#">
<input type="text" required="required" placeholder="Required text" />
<input type="email" required="required" placeholder="email" />
<button id="btn" type="button">Submit</button>
</form>
JavaScript:
$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity())
{
alert('validated');
}
else
{
//show errors
return false;
}
});
http://jsfiddle.net/5ycZz/

Try
reportValidity()
So you'd have
$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity()) {
alert('validated');
}
else {
$("#the-form")[0].reportValidity();
}
});

I've achieved this by doing steps below:
1) I'm having form:
<form>
<textarea required></textarea>
<input type="submit" style="display:none;"/>
</form>
<a>Some other button to trigger event</a>
2) Now we have to check if the form is filled correctly:
//this is <a> click event:
if (!$('form')[0].checkValidity()) {
$('form').find('input[type="submit"]').click();
return false;
}
This will trigger form sending but won't send because there are errors ;)
It appears that html5 validation errors are displayed on input[type="submit"] click :)
Hope will work for You too! :)

here is the perfect answer
<form id="the-form" action="#">
<input type="text" required="required" placeholder="Required text" />
<input type="email" required="required" placeholder="email" />
<button id="btn" type="submit">Submit</button>
$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity())
{
alert('validated');
}
else
{
return 0;
}
});

Remove the else statement. (Update)
$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity())
{
alert('validated'); //will appear if name and email are of valid formats
}
});

You should be able to simply add onclick="return validateForm()".
<button id="btn" onclick="return validateForm()" type="button">Submit</button>

Related

Struggling to validate the email when toggling

The HTML Code:
<div class="form-container">
<form method="post" id="email">
<div class="form-group">
<label for="exampleInputEmail1" class="typingA spacing"><i class="bi bi-envelope"></i> Email Address:</label>
<input type="email" class="form-control" id="typingEmail" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</form>
<form method="post" id="subject">
<fieldset class="form-group">
<label for="subject" class="typingA spacing">Subject:</label>
<input type="text" class="form-control"name="subject"placeholder="Subject" >
</fieldset>
</form>
<form method="post" id="content">
<fieldset class="form-group">
<label for="content" class="typingA spacing">What would you like me to ask?</label>
<textarea class="form-control" name="content" rows="3" placeholder="What would you like me to ask, Sir/Madam?"></textarea>
</fieldset>
</form>
<div id="buttons">
<button type="submit" id="next" class="btn btn-primary" enabled='enabled'>Next</button>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</div>
The JQuery part:
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("#buttons").click(function() {
$("#next").click(function() {
if(isEmail($('#typingEmail').val()) == false)
{
$(':input[type="submit"]').prop('disabled', false);
}
$("#subject").toggle();
$("#email").toggle();
$("#next").click(function() {
$("#content").toggle();
$("#email").toggle();
$('#next').attr('disabled', true);
});
});
});
What I am trying to do is validate the email. if it is valid, the "next button" should enable, else it should not enable. I tried but didn't succeed. I appreciate your time and help. Ta!
Note I tried to find similar topic on StackOverflow but didn't find it. So, just a humble
request, dont report.
I think you just want to disable and enable the next button when the email is valid or not valid, here is a workaround, i don't know whether it cover your requirement or not.
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$(function(){
var $emailInput = $('#typingEmail');
var $nextBtn = $('#next');
function checkIfEmailOk(){
return isEmail($emailInput.val());
}
function toggleNextByEmail(){
$nextBtn.prop('disabled', !checkIfEmailOk());
}
// or you can listen the 'blur' event
// but the validation will only triggered after your cursor moved out from the input area
// and the 'input' event may need some polyfill in lower versions of IE
$emailInput.on('input', function(){
toggleNextByEmail();
});
// disable the next button's onclick event when the email is not valid
$nextBtn.on('click', function(e){
if(!checkIfEmailOk()){
// email not ok
e.preventDefault();
$emailInput.focus();
}
});
// if you want to check the email input and toggle the next button when domready
toggleNextByEmail();
});
You can try it in the codepen.

Prevent submitting of form when pressing enter for 1 input

I have already seen this answer, but I want to disable the submitting of the form when pressing enter only for 1 input.
<form>
<input type="text" name="enterNotDisabled">
<input type="text" name="enterDisabled">
<button type="submit">
</form>
For example, I want that when the focus is on the first input, you can submit the form by pressing enter, but this feature would be disabled for the second input.
Thank you for your help.
just catch the "Enter" key event on that field.
Simple example :
<form>
<input type="text" name="enterNotDisabled">
<input type="text" name="enterDisabled" id="input2">
<button type="submit">
</form>
JS
function catchSubmit(evt) {
if (evt.code === 'Enter') {
evt.preventDefault();
}
}
document.getElementById('input2').addEventListener('keypress', catchSubmit, false);
Javascript
<form id="form">
<input type="text" name="enterNotDisabled">
<input type="text" name="enterDisabled">
<button type="submit">
</form>
<script type="text/javascript">
document.querySelector("#form").addEventListener("submit", function(e){
console.log('event')
e.preventDefault();
});
</script>
jQuery
<form id="form">
<input type="text" name="enterNotDisabled">
<input type="text" name="enterDisabled">
<button type="submit">
</form>
<script type="text/javascript">
$('#form').submit(function(ev) {
console.log('event')
ev.preventDefault();
});
</script>

How to know which form I clicked with button class

How can I know which form I clicked? Is it possible with a button class instead of buttons with id?
$(document).ready(function () {
$(".form-buttons").click(function () {
//I only want the form which corresponds to the button I clicked
var formDates = $(form).serialize()
alert ("You clicked "+formDates)
})
})
<form id="form1">
<input type="text" value="date1" name="name1"/>
<input type="text" value="date2" name="name2"/>
<input type="text" value="date3" name="name3"/>
<button type="button" class="form-button"></button>
</form>
<form id="form2">
<input type="text" value="date4" name="name1"/>
<input type="text" value="date5" name="name2"/>
<input type="text" value="date6" name="name3"/>
<button type="button" class="form-button"></button>
</form>
Yes use class instead of id for similar elements. Please try this.
Note: form-button is the class name in your HTML and not form-buttons
$(document).ready(function () {
$(".form-button").click(function () {
var formDates = $(this).closest('form').serialize();
alert ("You clicked "+formDates)
})
})
I think you be looking for
$('.form-button').on('click', function () {
alert($(this).parents('form').attr('id')); // Check the ID of the form clicked
});
something Maybe Like mentioned above.
You can get the name of the element by using the this keyword which refer, in a DOM event, to the cibled element :
$(document).ready(function () {
$(".form-buttons").click(function () {
alert('You clicked the form' + this.parentElement.getAttribute('id'));
})
})
You can do this in a few different ways. You can traverse up the DOM and see which form is used or -and this is my favorite- you can submit the form!
Solution 1: Traversing up the DOM
<script>
$(document).ready(function () {
$(".form-button").click(function () {
var clicked_form = $(this).parent();
var formDates = clicked_form.serialize();
alert ("You clicked "+formDates);
})
})
</script>
</head>
<body>
<form id="form1">
<input type="text" value="date1" name="name1"/>
<input type="text" value="date2" name="name2"/>
<input type="text" value="date3" name="name3"/>
<button type="button" class="form-button"></button>
</form>
<form id="form2">
<input type="text" value="date4" name="name1"/>
<input type="text" value="date5" name="name2"/>
<input type="text" value="date6" name="name3"/>
<button type="button" class="form-button"></button>
</form>
</body>
Solution 2: Submit the form
You already are using the form, so why not submit it? Change the buttons to input elements with type submit and intercept the submit event, like this. This is how I think it should be done. It is also better for user experience because the user can just submit the form by pressing enter.
<script>
$(document).ready(function () {
$("form").on('submit', function (e) {
e.preventDefault();
var formDates = $(this).serialize()
alert ("You clicked "+formDates)
})
})
</script>
</head>
<body>
<form id="form1">
<input type="text" value="date1" name="name1"/>
<input type="text" value="date2" name="name2"/>
<input type="text" value="date3" name="name3"/>
<input type="submit" class="form-button"></input>
</form>
<form id="form2">
<input type="text" value="date4" name="name1"/>
<input type="text" value="date5" name="name2"/>
<input type="text" value="date6" name="name3"/>
<input type="submit" class="form-button"></input>
</form>
</body>
Check this fiddle on how I would do it.
https://jsfiddle.net/xtfeugav/
Simple use
$("form").submit(function(e) {
to listen for every submit on all the forms you have. To get the ID of the form you use
var formid = $(this).attr('id');
I used e.preventDefault(); to prevent the form don't update the page.
Remember to use <input type="submit" value="Submit"> on your forms to make this work.
Its a simple code, hope it helps.

jQuery .on not working

I've seen this appear in a lot of places; however, after several hours, I still can't figure this simple thing out. Could someone verify my syntax is correct here?
$(document).ready(function(){
$("#login-form").on('submit', "#logout-btn", function() {
alert("The logout button was clicked.");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required>
<input type="password" placeholder="Password" id="formPwd" required>
<input id="logout-btn" type="submit" value="Login">
<input id="login-btn" type="submit" value="Logout">
</form><!-- login form -->
The submit event is triggered when a submit button is clicked, and there could be more than one, a button element without type="button|reset" is clicked. It can also be triggered by the Enter key.
You can use this to determine if the logout button was clicked. However, for form submission purposes, the submit event is by far the most reliable.:
$("#logout-btn").on('click', function(e) {
e.preventDefault(); //prevents default action.
alert("The logout button was clicked.");
});
$(function() {
$("#logout-btn").on('click', function(e) {
e.preventDefault(); //prevents default action.
alert("The logout button was clicked.");
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required/>
<input type="password" placeholder="Password" id="formPwd" required/>
<input id="login-btn" type="submit" value="Login"/>
<input id="logout-btn" type="submit" value="Logout"/>
</form><!-- login form -->
Another approach:
$(function() {
$(':submit').on('click', function(e) {
e.preventDefault();
if( $(this).is('#login-btn') ) {
alert('login-btn clicked');
} else if( $(this).is('#logout-btn') ) {
alert('logout-btn clicked');
} else {
alert('some other submit button clicked');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required/>
<input type="password" placeholder="Password" id="formPwd" required/>
<input id="login-btn" type="submit" value="Login"/>
<input id="logout-btn" type="submit" value="Logout"/>
</form><!-- login form -->
Try this:
$("#login-form").submit(function() {
alert("The logout button was clicked.");
});
Store the value of the last clicked button and in the .submit() event, make sure the last clicked button was the logout button. This works because the .click() event is fired before the .submit() event:
$(document).ready(function() {
//The logout button:
var logoutButton = $("#logout-btn");
//This variable holds the button in #login-form that the user last clicked:
var lastClicked = null;
//When the user clicks a button in #login-form, set it equal to lastClicked:
$("#login-form input[type=submit]").click(function() {
lastClicked = $(this);
});
//When the form is submitted, if it was the logout button, call the alert:
$("#login-form").on('submit', function() {
if (lastClicked.is(logoutButton)) {
alert("The logout button was clicked.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required>
<input type="password" placeholder="Password" id="formPwd" required>
<input id="login-btn" type="submit" value="Login">
<input id="logout-btn" type="submit" value="Logout">
</form><!-- login form -->
you have two submit button in your form, you can detrmine which was clicked like this.
$(document).ready(function() {
$("#login-form input[type=submit]").click(function() {
var clickedId = $(this).attr('id');
if(clickedId=="logout-btn")
alert("The logout button was clicked.");
else if(clickedId=="login-btn")
alert("The login button was clicked.");
});
});
Note that your Login button has the ID of the logout button and the other way around.
I'm gonna add an alternative to Peters answer, just for the sake of having an alternative.
Using onclick in the markup
function logOutClicked() {
alert("Logout button clicked!");
return true;
}
<form id="login-form">
<input placeholder="Username" id="formUsr" required>
<input type="password" placeholder="Password" id="formPwd" required>
<input id="login-btn" type="submit" value="Login">
<input id="logout-btn" type="submit" onclick="return logOutClicked();" value="Logout">
</form>
Using .bind()
Since we have a linear compilation of JavaScript, the first event that will be bound to the logout button in this case is the click event.
$(document).ready(function() {
$('#logout-btn').bind('click', function() {
alert('Logout clicked click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required>
<input type="password" placeholder="Password" id="formPwd" required>
<input id="login-btn" type="submit" value="Login">
<input id="logout-btn" type="submit" onclick="return logOutClicked();" value="Logout">
</form>

Validating messages before submit

I'm making a html5 application which require all fields to be filled in before the submit button can be clicked.
What I want to do now is give an alert if a textbox is not filled in, the problem is that my submit button is disabled until all fields are filled in, so I can't really add an alert to that button.
Any idea's on how to solve this?
I want it so that after filling in the final textbox the submit button becomes available without first having to click on it.
Note that the 'required' does not work.
I have the following code:
HTML:
<form id="winForm">
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
</p>
<p>
<input type="text" id="telefon" name="telefon" onclick="generateFullAdress()" required />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="sendTheMail()" value=" ">
</button><div id="loading"><img src="images/loadingBar.gif" id="load"></img></div>
</p>
</form>
Jquery/JS
<script type="text/javascript">
function generateFullAdress() {
document.getElementById('fullemail').value =
document.getElementById('email1').value + '#' +
document.getElementById('email2').value;
}
</script>
<script>
var $input = $('input:text'),
$register = $('#submitBtn');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
if(trigger) {
$register.attr('disabled',true);
}else {
$register.removeAttr('disabled');
}
});
</script>
Help would greatly be appreciated.
Thanks!
If you have a form as such:
<form id="form">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$(function() {
$('#form').submit(function() {
// DO STUFF
return true; // return false to cancel form action
});
});
OR
perform the samething with the onsubmit event like
<form action="youraction" onsubmit="validatefunction" method="post">

Categories

Resources