HTML5 validation does not trigger when fields are not accesible - javascript

I have a form with multiple fields, and I need to scroll 10-15 fields until the submit button. I want to check if the form is valid or not via jquery. If the first field of my form is required and I click on the submit button the field borders are going red but the message is not displayed. If I remove all the required fields from the top and just add the last fields as required the message is displayed. If I resize the browser to be able to see the first field when press the submit the validation message is displayed. Does this function (reportValidity) work with not accessible fields?
$('form').each(function() {
var $form = $(this);
$form.find(':submit').on({
'mousedown': function(e) {
var form = $(this).closest('form')[0];
if (form.checkValidity()) {} else {
form.reportValidity();
}
},
});
});
.test {
margin-bottom: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<input type=submit>
</form>

It can be solved by adding event.preventDefault() before the reportValidity() call.

Related

How to show and hide a form?

When I load a page, I need to show form for name, but when I click "submit" i need hide that form. How can i do that with javascript?
<div id="small-form">
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<input type="submit" value="Submit" onclick="hideForm()">
</form>
</div>
In the hideForm() function set display:none style for the div small-form.
Like that:
var myFormDiv = document.getElementById("small-form");
myFormDiv.style.display = "none";
You cannot just hide the form if it submits to the server unless you either Ajax the form to the server or target an iframe or new tab
When the form submits, a new page is loaded. If it loads the same page, you can either hide it on the server or set an instruction in localStorage to tell the page to not show the form
I also strongly suggest you do NOT use onclick of a submit button but the submit event
document.getElementById("myForm").addEventListener("submit",function(e) {
e.preventDefault(); // if you want to NOT submit the form
document.getElementById("small-form").classList.add("hide");
// here you can ajax or do other stuff without submitting
})
.hide { display: none; }
<div id="small-form">
<form id="myForm">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<input type="submit" value="Submit">
</form>
</div>
You can set the display style to none in the hideForm() function in javascript to hide the form.
But, because you are using a submit button on the form it will try to redirect when the submit button is pressed. A simple solution to this (if you don't want the form to actually be submitted) is to change the type of the input to button rather than submit.
function hideForm()
{
document.getElementById('small-form').style.display = 'none';
}
<div id="small-form">
<form >
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<input type="button" value="Submit" onclick="hideForm();">
</form>
</div>
If you wish to permanently hide the form you can do something like this. Just set the display property of the form to none. This will hide the form but it will exist there in the HTML code.
function hideForm() {
event.preventDefault();
var myForm = document.getElementById("My-Form");
myForm.style.display = "none";
var name = document.getElementById("Name");
alert(name.value);
}
<div id="small-form">
<form id="My-Form">
<label for="fname">First name:</label><br>
<input id="Name" type="text" id="fname" name="fname"><br>
<input type="submit" value="Submit" onclick="hideForm(event)">
</form>
</div>
Another way to achieve what you are trying to do is simply remove the form. You can do this by calling remove() function on the form. This permanently removes the form.
function hideForm(event) {
event.preventDefault();
var myForm = document.getElementById("My-Form");
var name = document.getElementById("Name");
alert(name.value);
myForm.remove();
}
<div id="small-form">
<form id="My-Form">
<label for="fname">First name:</label><br>
<input id="Name" type="text" id="fname" name="fname"><br>
<input type="submit" value="Submit" onclick="hideForm(event)">
</form>
</div>

How to make "focus" on input field on page load

When i click on input then "focus" jquery is working fine, but when i load page then "email-field" has curser, my goal is that if input has curser on page load this should be foucus and also add 'class is-focused' , which is add on input click.
PLease help me.
or if we can do this by add class on fieldset then anyone type any value in input.
// For input focused animation
$("input:text:visible:first").focus();
$(function() {
$("input:text:visible:first").focus();
// Trigger click event on click on input fields
$("form input.form-control, form textarea.form-control").on("click, change, focus", function(e) {
removeFocusClass();
// Check if is-focused class is already there or not.
if(!$(this).closest('form fieldset').hasClass('is-focused')) {
$(this).closest('form fieldset').addClass('is-focused')
}
});
// Remove the is-focused class if input does not have any value
$('form input.form-control, form textarea.form-control').each(function() {
var $input = $(this);
var $parent = $input.closest('form fieldset');
if ($input.val() && !$parent.hasClass('is-focused')) {
$parent.addClass('is-focused')
}
});
// Remove the is-focused class if input does not have any value when user clicks outside the form
$(document).on("click", function(e) {
if ($(e.target).is("form input.form-control, form textarea.form-control, form fieldset") === false) {
removeFocusClass();
}
});
function removeFocusClass() {
$('form input.form-control, form textarea.form-control').each(function() {
var $input = $(this);
if (!$input.val()) {
var $parent = $input.closest('form fieldset');
$parent.removeClass('is-focused')
}
});
}
});
fieldset.is-focused input {
border:5px solid red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form class="user-login-form">
<div class="form-head"><h2 >Sign in</h2>
<div class="description-text" ><p class="small-text" data-drupal-selector="edit-line1">Not a member yet?</p>
Register now<p class="small-text" data-drupal-selector="edit-line2"> and join the community</p>
</div>
</div>
<fieldset class="js-form-item js-form-type-textfield form-type-textfield js-form-item-name form-item-name form-group col-auto">
<input type="text" id="edit-name--MmB1Jbss54g" name="name" value="" size="60" maxlength="254" placeholder="Email address" class="form-text required form-control" required="required" aria-required="true" autofocus>
<label class="option js-form-required form-required">Email address</label>
</fieldset>
<fieldset class="js-form-item js-form-type-password form-type-password js-form-item-pass form-item-pass form-group col-auto">
<input type="password" id="edit-pass--Db3_6vLkpJQ" name="pass" size="60" maxlength="128" placeholder="Password" class="form-text required form-control" required="required">Show
<label for="edit-pass--Db3_6vLkpJQ" class="option js-form-required form-required">Password</label>
<small id="edit-pass--Db3_6vLkpJQ--description" class="description text-muted">
<p class="small-text">Forgot your password? Click here</p></small>
</fieldset>
</form>
</body>
</html>
You just need to add class in fieldset on page load. you can do with one single line code.
$("input:text:visible:first").closest('form fieldset').addClass('is-focused');
You can also refer jsfiddle url here

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.

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">

How to call javascript method on button click after the form inputs have been validated

I have an ASP.NET MVC web page which is essentially a form to fill in and select certain fields. I am using twitter bootstrap as well.
My.cshtml
#{
ViewBag.Title = "MyWork";
}
#section Scripts {
#Scripts.Render("~/scripts/mywork.js")
#Scripts.Render("~/scripts/typeahead.min.js")
}
<br />
<legend>Add items to enable work</legend>
<div class="row">
<div class="col-md-2">
Item name:
</div>
<div class="col-md-8">
<input id="ItemTextBox" name="Name" type="text" placeholder="Enter an item name ..." class="form-control" required="required" autofocus="autofocus" />
</div>
</div>
<legend>Generate file</legend>
<input id="GenerateFile" type="submit" class="btn btn-primary" value="Generate File" onclick="javascript:generateFile()" />
The javascript file mywork.js contains the generateFile() method and creates a file using the items entered.
How should I validate that the ItemTextBox is not empty? There can be a number of items added so I obviously don't want to check for each text element. I have set the required="required" for the inputs. How can I auto-validate the required fields?
Without any plug-in, for browser's default validation,
wrap your input elements with <form></form>. And add "required" attribute to all required input fields.
<form id="myform">
<p><span>Item 1</span> <input name="Item 1" type="text" placeholder="Enter an item name"required="required" autofocus="autofocus" /></p>
<p><span>Item 2</span> <input name="Item 2" type="text" placeholder="Enter an item name"required="required" autofocus="autofocus" /></p>
<p><span>Item 3</span> <input name="Item 3" type="text" placeholder="Enter an item name"required="required" autofocus="autofocus" /></p>
<p><input type="submit" value="Generate File"/></p>
</form>
Call generateFile function when form get submitted (your form won't get submitted until all required fields are filled) and prevent browser from submitting form to server.
document.getElementById('myform').onsubmit = function(e) {
generateFile();
e.preventDefault();
}
function generateFile(){
alert('Generating File');
}
DEMO
I think this link might help you:
Jquery Validation plugin
As you have added a "required" attribute, you can just validate a form and then call your javascript method using the above plugin:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
did you tried jQuery validation engine, its a nice and best plugin to validate your form controls very easily. Just have a look at below link (its a demo)
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
To download and for documentation visit
https://github.com/posabsolute/jQuery-Validation-Engine

Categories

Resources