Form action is not interrupted by "required" inputs - javascript

I have the following HTML code.
function document_save_changes(){
if (is_key_dirty == true){
var elm = document.getElementById('set_doc_button');
key_change_warning(elm, 'D');
return;
}
if (document_save_warning('A') == false){
return;
}
collect_nonkey_data();
do_recaptcha();
}
<form id="email_form">
<div id="email_table" class="emltbl inbtop" style="margin:auto;">
<div class="emlrow">
<div class="emlcll">Name:</div>
<div class="emlcll"><input class="email_input" type="text" name="email_1" id="email_1" placeholder="First and last name" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Email:</div>
<div class="emlcll"><input class="email_input" type="email" name="email_2" id="email_2" placeholder="Return email address" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Messg:</div>
<div class="emlcll"><textarea class="email_textarea" name="email_3" id="email_3" placeholder="Message to admin" required autocomplete="off"></textarea></div>
</div>
</div>
<div id="email_recaptcha" class="g-recaptcha" data-sitekey="key goes here"></div>
<div><button id="set_doc_button" type="button" style="padding:0.3em 1em;" disabled="disabled" autocomplete="off" onclick="document_save_changes();" title="Submit changes to data">Submit Data</button></div>
</form>
My problem is that the "required" INPUT elements are not causing the form submission to fail when the INPUT elements are not filled properly. (For instance, by the type="email" INPUT element which requires special syntax.)
How do I make it so that the "required" INPUTs interrupt the form action if they are not filled in properly? Thanks.

This is because you're not submitting the form. Making a button at the last of type button doesn't make it a submit button. You'll have to specify the type='submit' explicitly to make a button submit the form.
And now to the second part,
If you're trying to submit the form from JS function. The HTML5 validation won't work.
Inshort they are only in action when form is submitted with a button of type submit inside that form. And if you do want to use a button of type button and submit the form with JS, you'll have to check for validation in your JS code.
And in your JS code you can use checkValidity() function on any form to check if it's a valid from or not and then run the other things accordingly
var form = document.getElementById("email_form");
function document_save_changes() {
//Do your things
if (form.checkValidity()) {
form.submit();
} else {
alert("Something worng yet")
}
}
<form id="email_form">
<div id="email_table" class="emltbl inbtop" style="margin:auto;">
<div class="emlrow">
<div class="emlcll">Name:</div>
<div class="emlcll"><input class="email_input" type="text" name="email_1" id="email_1" placeholder="First and last name" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Email:</div>
<div class="emlcll"><input class="email_input" type="email" name="email_2" id="email_2" placeholder="Return email address" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Messg:</div>
<div class="emlcll"><textarea class="email_textarea" name="email_3" id="email_3" placeholder="Message to admin" required autocomplete="off"></textarea></div>
</div>
</div>
<div id="email_recaptcha" class="g-recaptcha" data-sitekey="key goes here"></div>
<div><button id="set_doc_button" type="button" style="padding:0.3em 1em;" autocomplete="off" onclick="document_save_changes();" title="Submit changes to data">Submit Data</button></div>
</form>

try this one
Use button type='submit' instead of button
<button id="set_doc_button" type="submit" style="padding:0.3em 1em;" autocomplete="off" onclick="document_save_changes();" title="Submit changes to data">Submit Data</button>
and remove disabled="disabled" after that your form will submit

Related

Field with removed 'required' attribute keeps validating after submit

I have a form to submit several fields. Two of them are for changing a password.
These password fields aren't required to be filled out before submitting. However, if one of them isn't blank I add the required attribute to both fields when it's changed through jQuery. I remove the attributes when I empty one and the other is already empty too.
The thing it seems to work the most of the times with an exception:
I fill out password
password2 is blank
I submit the form
In this case the validation for password2 shows up, but if I want to remove everything and submit, I can't:
I remove password
I submit the form again
The validation for password2 shows up again. Even if the 'required' attributed is removed in the HTML source
This is the HTML code:
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>
And the jQuery code:
$('#password').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$( '#password2' ).attr('required', true);
}else{
if($('#password2').val() == ''){
$(this).removeAttr('required');
$( '#password2' ).removeAttr('required');
}
}
});
$('#password2').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$('#password').attr('required', true);
}else{
if($('#password').val() == ''){
$(this).removeAttr('required');
$('#password').removeAttr('required');
}
}
});
And it's an example in JSFiddle:
https://jsfiddle.net/jke3pgh0/
I will suggest you a different approach here...
First, you only need one handler for this, since the logic is the same for both inputs. You can use more than one selector... Ex: $('#password, #password2'). But I would use a class instead... Like $(".password"). It's up to you.
Second, I said the «logic is the same»... That is:
If one of the two inputs is not empty, both are required.
So having the same change event handler on both inputs mean you don't really know which one triggered the event. So I suggest to use an .each() loop here (to make sure you check all values)... and a boolean "flag" (true/false).
After that loop, use that "flag" to set the required attribute.
I used a CSS rule to make the result obvious in the snippet below.
$('#password, #password2').change(function(){
// Look up for the password inputs in that "row".
var pass_inputs = $(this).closest(".row").find("[type='password']");
// Flag to determine if at least one is not empty.
var not_empty = false;
// Loop throug the password inputs and change the flag.
pass_inputs.each(function(){
if($(this).val() != ''){
not_empty = true
}
});
// Use the flag as the boolean argument for the required attribute.
pass_inputs.attr('required', not_empty);
});
[required]{
border: 3px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>

Jquery to check if form fields are required before modal pop up

Hi have a form which has two submit buttons:
(Button 2)The user clicks the submit button and a modal pop up appears and in the modal is some T&Cs they have to accept, (Button 1) once they click accept the second submit button does the form submission.
There are required form fields that don't show (required) once the first button is pressed just the modal pop up comes, How can I achieve this? My Jquery code is:
$(document).ready(function () {
$("#login-form button").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "button1") {
// alert("First Button is pressed")
$("#login-form").submit();
}
if ($(this).attr("value") == "button2") {
$(".modal").addClass("active");
}
});
});
The form field is:
<label class="form-label" for="firstname">First name:</label>
<input class="form-input" required type="text" name="firstname" id="firstname" value="firstname>
Any ideas?
Here is a little code i wrote, i try to make it as dynamic as possible.
Instead of click you should have it onchange but its really upp to you.
make sure too look at validationType
$("input[type='button']").click(function(){
if ($(this).hasClass("disable"))
return false;
if ($(this).hasClass("validate")){
var errors = [];
// all required input that need validation
var input = $(this).parent().find("input[type='text'][required='required']");
input.each(function(){
var vType= $(this).attr("validationType");
var value =$(this).val();
var fName =$(this).attr("placeholder");
switch(vType){
case "notEmpty":
if (!value || value== "")
errors.push(fName +" cant be empty");
break;
}
});
if (errors.length>0){
$(this).parent().find(".submit").addClass("disable");
alert(errors)
}
else {
$(this).parent().find(".submit").removeClass("disable");
}
}else return true; // submit the form
});
input[required="required"]{
border:1px solid red;
}
.disable{
color:#CCC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" validationType="notEmpty" required="required" value="" placeholder="firstName" />
<input type="button" class="validate" value="button 1" />
<input type="button" class="submit disable" value="button 2" />
</form>
Ok this is how steps works on my own way .. The idea here is the first form is a main one and the second is a just for users not for programming .. This means the first form will have all the required fields and I will hide the fields and control it with javascript from the fake form
I create two forms one is a main and the second is a fake one
I add a hidden checkbox in a main form
I make separated submit events for each form
I made a change event for the fake checkbox to control the main checkbox in the main form
$(document).ready(function(){
// Main Form Submit
$("#mainForm").on("submit" , function(e){
e.preventDefault();
if($("#mainCheck").is(":checked")){
alert("First Form is Submitted correctly");
}else{
//alert('Show Modal With Form');
$("#fakeForm").show();
}
});
// Fake form in Modal submit
$("#fakeForm").on("submit" , function(e){
e.preventDefault();
if($("#fakeCheck").is(":checked")){
$("#mainForm").submit();
}else{
alert("Please Accept our policies first");
}
});
// fake checkbox to change main checkbox
$("#fakeCheck").on("change" , function(){
$("#mainCheck").prop("checked" , this.checked);
});
});
#mainForm, #fakeForm{
background : #eee;
border : 5px solid #555;
margin : 20px;
padding : 20px;
}
#mainCheckLabel,#fakeForm{
display : none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- first Form -->
<form id="mainForm">
<label class="form-label" for="firstname">First name:</label>
<input class="form-input" required type="text" name="firstname" id="firstname" value="firstname" />
<br/>
<label id="mainCheckLabel"><input type="checkbox" id="mainCheck"/>Accept to our policies</label>
<button type="submit">Submit First Form</button>
</form>
<!-- End First Form -->
<!-- Second Form in Modal -->
<form id="fakeForm">
<label id="fakeCheckLabel"><input type="checkbox" id="fakeCheck"/>Accept to our policies</label>
<button type="submit">Submit Second Form</button>
</form>
<!-- End Second Form in Modal -->
Note hide the #mainCheckLabel in the main form
Example of how to use [required] selector
$('input[required]').css('border' , '1px solid red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" required placeholder="First Name"/>
<input type="text" placeholder="Last Name"/>
Following solution works for me:
$("#uploadBtn").click(function() {
var form_data = new FormData($("#data-uploader-form")[0])
if ($("#data-uploader-form")[0].checkValidity()) {
alert("valid form")
} else {
alert("incorrect form")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='data-uploader-form' onsubmit='return false;'>
<div class="form-group row">
<label>Input field</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="testInputField" placeholder="some text" required="required">
</div>
</div>
<div class="form-group row">
<label class="col-12 col-lg-3 col-form-label"></label>
<div class="col-12 col-lg-6">
<button type="submit" class="btn btn-primary float-left" id="uploadBtn">Submit</button>
</div>
</div>
</form>

JavaScript : Enable button if field is filled is not automatical

function checkValid() {
var cbChecked = $(".fakeRadio").is(":checked"); // check if checked
var hasText = $("#email-download-document").val().length > 0; // check if it has text
$("#document-choice-button").prop("disabled", !cbChecked || !hasText);
}
$(function() {
checkValid(); // run it for the first time
$(".fakeRadio").on("change", checkValid); // bind checkbox
$("#email-download-document").on("change", checkValid) // bind textbox
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="row">
<div class=" col-md-5">
<label for="primary">Email address</label>
<input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument" placeholder="Enter email address to get document(s)">
</div>
</div>
<br>
<div class="row">
<div class=" col-md-5">
<input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected" value="{% trans 'Send to my email' %}" />
</div>
</div>
I would like to get your help because I have a little issue with my simple Javascript part and Chrome Browser.
With Chrome, my button is greyed out until I click outside of the field when this one is filled. I would like to enable my button when the field is automatically filled with email verification thanks to type='email'.
This is an example :
Try with input event instead of change.
The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
function checkValid() {
var cbChecked = $(".fakeRadio").is(":checked"); // check if checked
var hasText = $("#email-download-document").val().length > 0; // check if it has text
$("#document-choice-button").prop("disabled", !cbChecked || !hasText);
}
$(function () {
checkValid(); // run it for the first time
$(".fakeRadio").on("input", checkValid); // bind checkbox
$("#email-download-document").on("input", checkValid) // bind textbox
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class=" col-md-5">
<label for="primary">Fake Radio</label>
<input type="radio" class="fakeRadio" checked>
<label for="primary">Email address</label>
<input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument"
placeholder="Enter email address to get document(s)">
</div>
</div>
<br>
<div class="row">
<div class=" col-md-5">
<input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected"
value="Send to my email"/>
</div>
</div>
Try to use 'input' event instead of 'change' event in your Javascript, to trigger the function when the user is typing into the field.
Have your HTML button by default disabled
<input id="document-choice-button" type="submit" ... disabled="disabled" />
This way, it will load disabled without any javascript.
Then, attach a function to keyup event of your textbox to check if the length of the current text is greater than zero.
$("#email-download-document").keyup(function(){ // triggered at any keystroke
if ($(this).val().length>0) {
$("#document-choice-button").removeProp("disabled"); // enable the field
} else {
$("#document-choice-button").prop("disabled","disabled"); // disable the field
}
});
PS: This will make the button enabled/disabled as you are typing or clearing text from the textfield. If you would like to only disable/re-enable after you have exited the textfield, then you will need to attach the function to the change event
$("#email-download-document").change(function(){ //triggered after leaving textbox
if ($(this).val().length>0) {
$("#document-choice-button").removeProp("disabled");
} else {
$("#document-choice-button").prop("disabled","disabled");
}
});
$("#email-download-document").keyup(function(){
if ($(this).val().length>0) {
$("#document-choice-button").removeProp("disabled");
} else {
$("#document-choice-button").prop("disabled","disabled");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="row">
<div class=" col-md-5">
<label for="primary">Email address</label>
<input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument" placeholder="Enter email address to get document(s)">
</div>
</div>
<br>
<div class="row">
<div class=" col-md-5">
<input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected" value="{% trans 'Send to my email' %}" disabled="disabled" />
</div>
</div>

AngularJS validation on submit

I have a register form that I wish to do validation on the moment a user clicks submit. This is what the HTML looks like:
<form ng-submit="RegistrationC.fireReg()" novalidate name="register">
<div class="row">
<div class="col-md-6 form-group">
<input type="text" autocomplete="off" class="form-control" placeholder="First Name" ng-model="RegistrationC.first_name" required name="first_name">
<div class="help-block" ng-messages="register.first_name.$error" ng-show="submitted && register.first_name.$error">
<p ng-message="required">This field is required.</p>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 form-group col-md-offset-3">
<button type="submit" class="btn btn-success btn-block" ng-click="submitted=true">Register Now</button>
</div>
</div>
</form>
It is showing the validation message if a username is not typed in, but it still submits. What am I missing?
EDIT 1
//init.js - RegistrationController
reg_list.fireReg = function () {
var url = 'user/register';
api.makeCall(reg_list, url)
.then(function (response) {
reg_list.response = response;
console.warn(response);
$location.path('/user/verify');
})
.catch(function (errorMessage) {
console.log("got an error in initial processing", errorMessage);
event.restoreButton();
});
};
I know there's issues in this function, I will fix them at a later stage.
Submit this form only if it is valid. <whatever_form_name>.$valid
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">
Just add checkpoint whether form is valid or not before submitting form
Try like this
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">
If you want to disable html5(or browser) validator, You have to remove 'required' attribute in your html code
http://www.the-art-of-web.com/html/html5-form-validation/
http://www.w3schools.com/tags/att_input_required.asp

How to show success message after validation

I want to valid some fields and I want to show success message $('.alert-success').show(); after user entered all values.
I tried here jsfiddle Now I am able to validate all fields but I don't know how to show success message if all fields are not null.
Html:
<div class="contentContainer">
<div class="alert alert-success hide">Form submitted successfully</div>
<div id="basicInfo">
<div class="toggleContentInnerSec">
<div class="row-fluid">
<div class="span7">
<label>First Name</label> <br>
<p class="hide firstNameErrorMsg error">Please enter first name</p>
<input type="text" name="borrowerBasicDetail.firstName" value="" id="addBorrowers_borrowerBasicDetail_firstName" class="access required" placeholder="Example: 'Sachin' " data-errormsg="firstNameErrorMsg"> <br>
<label>Last Name</label> <br>
<p class="hide lastNameErrorMsg error">Please enter last name</p>
<input type="text" name="borrowerBasicDetail.lastName" value="" id="addBorrowers_borrowerBasicDetail_lastName" class="access required" placeholder="Example: 'Tendulkar' " data-errormsg="lastNameErrorMsg"> <br>
<label>Date Of Birth</label> <br>
<p class="hide birthDayErrorMsg error">Please enter date of birth</p>
<input type="text" name="borrowerBasicDetail.age" value="" id="addBorrowers_borrowerBasicDetail_age" class="access required" placeholder="DD/MM/YYYY" data-errormsg="birthDayErrorMsg"> <br>
</div>
</div>
</div>
</div>
<div class="row-fluid pull-left">
<div class="form-actions">
<a class="btn btn-success btn-large" id="tabOneSubmit">Submit</a>
</div>
</div>
</div>
Script:
submit();
function submit(){
$('#tabOneSubmit').click(function(){
$('.required').each(function(){
var element=$(this);
var elementVal=$(this).val();
var errorMsgId=element.attr('data-errorMsg');
if(elementVal==''){
$('.'+errorMsgId).show();
element.addClass('errorField');
}
else{
$('.'+errorMsgId).hide();
element.removeClass('errorField');
}
});
});
}
Here is the solution, just set a status variable.
submit();
function submit(){
$('#tabOneSubmit').click(function(){
var status=true;
$('.required').each(function(){
var element=$(this);
var elementVal=$(this).val();
var errorMsgId=element.attr('data-errorMsg');
if(elementVal==''){
$('.'+errorMsgId).show();
element.addClass('errorField');
status=false;
}
else{
$('.'+errorMsgId).hide();
element.removeClass('errorField');
}
});
if(status) {
$('.alert-success').show();
}
});
}
Demo
$("#msg").html("Form was submitted");
First, using validator is a good thing but I suggest you check inputs in server side too, because it's easy to hack javascript code.
Secondly you need the encapsulate that your input fields via;
<form method="POST or GET" action="foo.html"> </form>
Then you can use jQuery submit() method to submit via javascript:
$(form).submit(function(){
$('.alert-success').show();
event.preventDefault(); // if you want to send data only, do not reload page.
});
$(form) can be like if form has id or class: $('.myForm') , $('#myForm')

Categories