Simple JQuery function will not execute after form submission - javascript

Simple JQuery function will not execute after form submission. I can see that my form values are sent but when function in reached, there is no execution. I've read several posts and removed the "submit" value from my button id and still JQuery will work. Any help direction would be greatly appreciated.
$(document).ready(function() {
//When the chat form is submitted
$("#chatform").submit(function(event) {
event.preventDefault();
//Take the values directly form the chat form//
var name = $("#uname").val();
var message = $("#message").val();
if (message != "" && name != "") {
$.post("clashofcolchatdata.php", {
message: message,
name: name
}, function(data) {
$("#chat_space").append(data);
});
} else {
alert("Data missing");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="chatform" action="">
<div id="chat_comform">
<!-- This is the blank space for the chat -->
<div id="chat_space">
</div>
<div id="chat_message">
<!--Name | Name of the user entering the message -->
<input type="text" placeholder=" Name" name="uname" id="uname" style="color:black" required/>
<br />
<!--Message | This is the chat message -->
<input type="text" placeholder=" Enter your chat message" name="message" id="message" style="color:black" required/>
<!-- This disables the button if anything on the is still invalid -->
<button type="submit" id="chat_submit" name="formsub" value="post" style="color:black">Submit</button>
</div>
</div>
</form>

change <form name="chatform">
to <form id="chatform">. You're querying by html id when you do $('#chatform') but you have not set an id on the form.

Related

How to show form validation errors in inputs NOT one by one in popups?

I have a very simple form here with 2 required inputs.
When you click submit button without filling them - there are popups saying that you should do it. The problem is that popups are showed one by one - for example, if both inputs arent filled, only the first input will have this popup. And when the first one is filled only then it goes to the second and vice versa.
Is there any way to show all the fields that are not filled/filled incorrect during the validation at the same moment? So the user sees immediately everything he/she has to fill?
I am quite new to this, so please help me find the solution in pure JS (if it is about JS).
Here is the code:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST">
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" required=""
oninvalid="setCustomValidity('Enter first name')" oninput="setCustomValidity('')"
placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" required=""
oninvalid="setCustomValidity('Enter last name')" oninput="setCustomValidity('')"
placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
The code you provided is using a built in function of JavaScript, setCustomValidity(). This most likely is the reason for the pop-up. Instead we can write a custom function to show a little paragraph/span with the text instead.
Here we have a HTML form, but with a call for the custom function validateFields(), when clicking the Submit button:
<form class="" action="your-post-page.html" method="post" id="my-form-id" name="my-form-name" onsubmit="return validateFields()" target="_blank" class="validate" novalidate="">
<input id="name_1" type="text">
<br><br>
<input id="name_2" type="text">
<br><br>
<input id="name_3" type="text">
<br><br>
<input type="submit" name="" value="SUBMIT FORM">
</form>
<p id="error_messages" style="background-color: red; color: white;"></p>
The JS that makes it happen:
(custom function that reacts to inputs being empty and lets the user know which fields need fixing, put code before the </html> tag in your html-page)
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["name_1", "name_2", "name_3"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["Name 1", "Name 2", "Name 3"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["my-form-id"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
Now lastly, here is your own code with this example:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST" onsubmit="return validateFields()" >
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
<!-- here I added a new box for the error messages in your code -->
<div class="">
<p id="error_messages" style="background-color: red; color: white;"></p>
</div>
</div>
</form>
</body>
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["first_name", "lastName"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["First name", "Last name"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["mainForm"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
</html>
That was with custom scripting to get a box that you can style and enhance yourself, in this case below the form. But if you are okay with some default (and perhaps not unified styling, due to browser differences) you can also just remove the JavaScript function you had in your original code, the setCustomValidity(''). That will leave you with a generic message using the already present attribute required="", which produces this:
To achive that behaviour, change your tags for each field to look like this instead:
<input id="first_name" name="first_name" type="text" value="" required="" placeholder="Enter first name">

How can I disable the popup success message when the form is required to fill?

I am planning to display a Success message when clicked on the Submit button.
However, I would like to disable or hide the Success message whenever the form is required to fill.
So how can I do it by changing the code in script?
Please help me, I really appreciate your support!
This is my code:
<div class="contact-wrapper">
<main class="flex-container">
<section class="main-content">
<form class="contact-form" action="index.html" method="post" onsubmit="return false">
<input type="text" class="contact-form-text" placeholder="Name" id="name" required/>
<input type="email" class="contact-form-text" placeholder="Email" id="email" required/>
<input type="text" class="contact-form-text" placeholder="Title">
<textarea class="contact-form-text" placeholder="Type your message..."></textarea>
<button>Send</button>
<div class="alert">
<span class="message">Success: You Message Sent Successfully!</span>
</div>
</form>
</section>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var name = document.getElementById('email').value;
}
$('button').click(function(){
$('.alert').addClass("show");
$('.alert').addClass("showAlert");
$('.alert').removeClass("hide");
setTimeout(function(){
$('.alert').addClass("hide");
$('.alert').removeClass("show");
},3000);
});
</script>
Consider hiding the message initially and display it only on successful submission
<div class="alert hide">
<span class="message">Success: You Message Sent Successfully!</span>
</div>
you should show the alert only if the form validation returns true.
function validateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
if(name == '' || name == null || email == '' || email == null){
alert("Please Fill All Required Field");
return false;
}
return true;
}
$('button').click(function(){
if(validateForm()){
// your code for submission
// after successful submission display the alert message
$('.alert').removeClass("hide");
$('.alert').addClass("show");
$('.alert').addClass("showAlert");
}
});
I would suggest you to follow the standard format for form validation and form submission. link here

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>

html javascript ajax jquery

I m validating variables from html inputs in ajax javascript .
What i m trying to do for sure is when client Click the Submit button which it variable is var sub another div from html file should appear but after completing to fill the required fields.
But when i tried doing it i get no response means the html div that should appear
HTML
<span id="formst">User name:<input type="text" name="username" id="user" onBlur="checkU();"/>
<div id="staut"></div>
<br /><br />
Phone Number:<input type="tel" name="number" id="tel" value="+255" />
<div id="stau"></div>
<br /><br />
<h3>Your Description</h3>
<textarea rows="6" cols="22" id="textarea" ></textarea><br /><br />
<input type="submit" value="submit" onClick ="payment();" id="sub"/>
<div id="st"></div>
</span>
</form>
<div id="payment2">
<ul id="adjustPay">
<li id="tigo" onClick="Tigo();">Tigo Pesa</li>
<li id="voda">Vodacom Mpesa</li>
<li id="air">AirTel Money</li>
</ul>
</div>
</div>
and ajax javascript Jquery code
var ajax = ajaxObj("POST", "function.php");
info.innerHTML = "Please wait ...";
ajax.onreadystatechange = function(){
if(ajaxReturn(ajax) == true){
if(ajax.responseText != "please wait"){
info.innerHTML = ajax.responseText;
sb.style.display = "block";
}else if(ajax.responseText = "please wait"){
$(document).ready(function(){
$("#form").show(function(){
$("#form").slideUp(3840);
$("#payment2").show();
});
});
}
}
}
ajax.send("u="+u+"&n="+n+"&t="+t);
}
Problem is on else if(ajax.responseTex = "please wait")
please if there is any way of doing this just show me
You need something like this - you need to change #sb and data to reflect the actual element and the data returned
$(function(){
$("#form").on("submit",function(e) { // when submitted
e.preventDefault(); // cancel the submission
$("#info").html("Please wait ...");
$.post(function.php",$("#form").serialize(),function(data) {
if (data != "please wait"){
$("#info").html(data);
$("#sb).show();
else {
$("#form").show(function(){
$("#form").slideUp(3840);
$("#payment2").show();
});
});
});

How do I show/hide a div on field validation with parsley.js

So I guess for context, here is an example from the parsley.js documentation.
<form id="demo-form" data-parsley-validate>
<div class="first">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" data-parsley-range="[4, 20]" data-parsley-group="block1" />
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" data-parsley-range="[4, 20]" data-parsley-group="block1" />
</div>
<hr></hr>
<div class="second">
<label for="fullname">Fullname:</label>
<input type="text" name="fullname" data-parsley-range="[8, 40]" data-parsley-group="block2" />
</div>
<div class="invalid-form-error-message"></div>
<input type="submit" class="btn btn-default validate" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#demo-form').parsley().subscribe('parsley:form:validate', function (formInstance) {
// if one of these blocks is not failing do not prevent submission
// we use here group validation with option force (validate even non required fields)
if (formInstance.isValid('block1', true) || formInstance.isValid('block2', true)) {
$('.invalid-form-error-message').html('');
return;
}
// else stop form submission
formInstance.submitEvent.preventDefault();
// and display a gentle message
$('.invalid-form-error-message')
.html("You must correctly fill the fields of at least one of these two blocks!")
.addClass("filled");
return;
});
});
</script>
Let's say I have a hidden div called "checkmark". How would I show this div upon validation of the firstname field?
I should also clarify that I have read the documentation, but still don't understand how to accomplish what I'm trying to do here, so posting a link to the documentation is not really going to be helpful unless you are using it in your answer.
You should use Parsley's Events. Since you want to display or hide something based on a field validation, you should use parsley:field:success and parsley:field:error.
Working example (with jsfiddle):
<form id="demo-form" data-parsley-validate>
<div class="first">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" data-parsley-range="[4, 20]" data-parsley-group="block1" required />
<div class="hidden" id="checkmark">This message will be shown when the firstname is not valid </div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" data-parsley-range="[4, 20]" data-parsley-group="block1" />
</div>
<hr></hr>
<div class="second">
<label for="fullname">Fullname:</label>
<input type="text" name="fullname" data-parsley-range="[8, 40]" data-parsley-group="block2" />
</div>
<div class="invalid-form-error-message"></div>
<input type="submit" class="btn btn-default validate" />
</form>
<script>
$(document).ready(function () {
$('#demo-form').parsley().subscribe('parsley:form:validate', function (formInstance) {
// if one of these blocks is not failing do not prevent submission
// we use here group validation with option force (validate even non required fields)
if (formInstance.isValid('block1', true) || formInstance.isValid('block2', true)) {
$('.invalid-form-error-message').html('');
return;
}
// else stop form submission
formInstance.submitEvent.preventDefault();
// and display a gentle message
$('.invalid-form-error-message')
.html("You must correctly fill the fields of at least one of these two blocks!")
.addClass("filled");
return;
});
$.listen('parsley:field:error', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('show').removeClass('hidden');
}
});
$.listen('parsley:field:success', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('hidden').removeClass('show');
}
});
});
</script>
And here's what I did:
Added a div with ìd=checkmark after the firstname field (with a hidden class, since you're using Bootstrap).
Added this block of javascript:
$.listen('parsley:field:error', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('show').removeClass('hidden');
}
});
$.listen('parsley:field:success', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('hidden').removeClass('show');
}
});
This code will listen to the validation of every input validated by Parsley. This means that when the field lastname fails, the code inside $.listen('parsley:field:error', function(ParsleyField) { will be executed. This is why I used an if to check if the attr name is firstname.
Then you show or hide the div based on the validation result.
Added required to the field, so the message is displayed when you click on the button.

Categories