How to show success message after validation - javascript

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')

Related

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>

Form action is not interrupted by "required" inputs

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

window.location.replace not working with jquery

I am having a little problem here for some reason. I have another page with almost the exact same code and it redirects the user to the page that I want them to go to. For some reason this one does not. I have tried commenting out the if statement and everything down to the point of just having the window.location.replace with the click action and still no luck.
JS
$(document).ready(() => {
$("#login-button").click(() =>{
if($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.replace('../index.html');
} else {
alert("You have the wrong password and username");
}
});
});
HTML
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
You're mistaking what location.replace() is used for. To redirect, use location.href instead.
window.location.href = '../index.html';
The Location.replace() method replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
You also need to prevent the form submit. This is causing the page to be posted back to itself. Add the following inside your form submit event handler.
e.preventDefault();
You just need to stop the default form submit
html
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
jQuery
$(function() {
$("#login-button").click((e) {
if ($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.href('../index.html');
e.preventDefault();
} else {
alert("You have the wrong password and username");
e.preventDefault();
}
});
});

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

javascript validation not happening

I have written the following form in my html file.
<form name = "myForm" method="post" action="" id="comment_form" class="comment_form" onsubmit="return validateForm()" >{% csrf_token %}
<div class="row-fluid">
<div class="span6">
<input type="text" id="email" name="email" placeholder="Email*">
</div>
<div class="span6">
<input type="text" id="name" name="name" placeholder="Name*">
</div>
</div>
<div class="row-fluid">
<div class="span8">
<textarea name="message" id="txt_message" placeholder="Message*" cols="30" rows="10"></textarea>
</div>
<div class="span4">
<button class="btn " type="button"><i class="li_paperplane"></i>Send message</button>
</div>
</div>
</form>
And I have added this javascript function inside my HTML file
<script>function validateForm()
{
var x=document.forms["myForm"]["name"].value;
var y=document.forms["myForm"]["email"].value;
var a=document.forms["myForm"]["message"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (x==null || x=="" ||y==null||y==""||a==""||a==null)
{
alert("All fields must be filled out");
return false;}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Please enter a valid e-mail address");
return false;
}
else{
alert("Thank you for your response");
return true;
}
}</script>
On click of Send Message button I am not getting any response from the javascript. The code looks fine and the same code is working on another HTML file. What seems to be the problem?
Your "Send Message" button is just a button -- it doesn't submit the form. You can either use an <input type="submit"> or use JavaScript on your <button> to submit the form.
You need to add an onclick event to your button. Add the following attribute to the button
Syntax:
onclick="document.NameOfTheForm.submit();"
So in this syntax you have to add following
onclick="document.myForm.submit();"

Categories