Jquery form gets send even if validation is invalid - javascript

I have a form which needs to be validated before getting submitted with axios.
<form method="POST" action="{{ route('application.store') }}" id="myForm" novalidate="">
<input name="name" type="text" class="form-control required" placeholder="Name" autocomplete="name" required>
<div class="invalid-feedback">
Please insert name
</div>
<input name="email" type="email" class="form-control required" placeholder="Email" autocomplete="email" required>
<div class="invalid-feedback">
Please enter email
</div>
etc. etc
<button type="submit" class="btn">Send</button>
</form>
then in my javascript I have:
$('button[type="submit"]').click(function(e) {
e.preventDefault();
$("#myForm .required").each(function(e) {
if ($.trim($(this).val()).length == 0) {
$(this).addClass("is-invalid");
$(this)
.closest(".invalid-feedabck")
.show();
} else {
$(this).removeClass("is-invalid");
sendApplication();
}
});
function sendApplication() {
// here is the axios post method...
}
});
So, when one of the inputs are empty, the invalid-feedback message gets displayed but the form gets submitted anyway, so what am I doing wrong?

Related

compare the value of two form email fields

I have created a form requiring email validation. So user must type in their email address twice and if they don't match they won't be able to submit. I did this by simply comparing the values of email fields 1 and 2. If they match "disabled" is removed from the submit button.
All was working perfectly when I had the value set to "Insert your email address and "confirm your email address again". However, so that the user does not have to delete that text, I removed the value and used "placeholder" in the HTML instead.
The problem now is that the moment you type anything it's returning as true. I guess it's seeing the blank values as the same, but it's not picking up on the changes to the value as the user types it in.
Why are the two fields always returning as a match?
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses
Do Not Match">
</form>
<script>
function verify (){
console.log(`email1.value: ${email1}: Email2: ${email2}`);
if(document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
}
}
$(".fields").on("change paste keyup", verify);
</script>
</body>
</html>
try this
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input id="submit" type="button" onclick="verify()" value="click">
</form>
<script>
function verify()
{
if(document.getElementById("email1").value === document.getElementById("email2").value) {
alert("matched")
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
alert("not matched")
}
}
</script>
</body>
</html>
This worked for me:
Change the email inputs to [type='email'].
Add the required attribute to #email1.
Add a check to the validity of #email1 in your conditional.
Reset styles to initial (or what you prefer) if the button is reset back to 'disabled'.
Use 'input' event to get the the values updating on every keystroke, 'change' only fires on 'blur' or when the form is submitted.
It'd end up looking like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="email" id="email1" class="fields" name="email" placeholder="Email Address" required>
<input type="email" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses Do Not Match">
</form>
<script>
function verify (){
console.log(`email1: ${email1.value}: Email2: ${email2.value}`);
if(document.getElementById("email1").checkValidity() && document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
document.getElementById("submit").style.backgroundColor = "initial";
document.getElementById("submit").style.cursor = "initial";
}
}
$(".theForm").on("input paste keyup", "input[type=email]", verify);
</script>
</body>
</html>
MDN Docs for input and change events:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Instead of:
$(".fields").on("change paste keyup", verify)
Try:
$(".fields").blur(verify)
EDIT:
How about:
$("#email2").blur(verify)
?

passing data from Javascript to Laravel controller

I'm getting the error of MethodNotAllowedHttpException when I run the below code:
<h1>Temp Form</h1>
<form method="post" action="" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="panel panel-default ">
<div class="container">
<div class="panel-body">
<div class="form-group">
<label for="firstName">First Name *</label>
<input name="fname" type="text" class="form-control" id="firstName" placeholder="Enter First Name" required>
</div>
<div class="form-group">
<label for="lastName">Last Name *</label>
<input name="lname" type="text" class="form-control" id="lastName" placeholder="Enter Last Name" required>
</div>
<div class="form-group">
<label for="qualification">Qualification *</label>
<input name="qualification" type="text" class="form-control" id="qualification" placeholder="BE, MCA, MBA Etc." required>
</div>
<div class="form-group">
<label for="emailAddress">Email address *</label>
<input name="email" type="email" class="form-control" id="emailAddress" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contactmessage">Message</label>
<textarea name="desc" type="text" class="form-control" id="contactmessage" placeholder="Message" rows="2"></textarea>
</div>
<input type="submit" id="add" class="btn btn-primary" onclick="addUpdateData(id)" value="Add"></button>
</div>
</div>
</div>
</form>
Code for routes.php :
Route::post('welcome/addupdate','FormController#addUpdateData');
code for controller :
public function addUpdateData(Request $req)
{
$id = $req->input('id');
if($id=="add")
{
$bs = new Basicusers;
$bs->fname = $req->fname;
$bs->lname = $req->lname;
$bs->qualification = $req->qualification;
$bs->email = $req->email;
$bs->desc = $req->desc;
$bs->save();
return "Data Successfully Added";
}
}
What I want is, when user clicks on add button, value in variable data add is passed, and on controller, I will check value for variable and if its add, than I will perform add operation.
meanwhile if the user click on edit button which is provided below in form, that row will be filled in form elements and the add button is changed to update button and value of variable data will be now update and I want to perform update operation...
I'm getting error when I am passing data using POST method
moreover I don't know how to get data passed using POST method..
for GET method I am using $id = Input::get('id'); method and its working
Here is JavaScript Function :
function addUpdateData(data) {
$(function() {
$.ajax({
method: "post",
url: "welcome/addupdate",
data: {
id: data
},
success: function(response) {
alert(response);
}
});
});
}
Try to use absolute path in your ajax request: url: "/welcome/addupdate"
Add a some ID for your form (ex. #form) and pass into the addUpdateData function serialized data from the form.
$('#add').on('click', function(e) {
e.preventDefault();
var data = $('#form').serialize();
addUpdateData(data);
});
Add also a input field as hidden type into the form which should have an ID of the existing resource. Then on the controller action you can get an array of the passed data and if if the ID of the resource exists the perform update. If not then create them.

Disable input until previous input is validated with bootstrap-validator

I am using bootstrap-validator and it works great for validation but I now need to disable an input until the previous input has been validated. I looked at the bootstrap-validator and I saw these events which look like they will help in this process, but I cannot figure out how to call them on an input id.
HTML
<form role="form" data-toggle="validator">
<div class="form-group">
<input type="text" class="form-control" id="login-name" placeholder="Your Name" data-error="Please provide a valid name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" id="chosen-name" placeholder="Your Chosen Name" data-error="Please provide a valid name" required disabled>
<div class="help-block with-errors"></div>
</div>
<button type="submit" class="btn btn-default action-btn">Submit</button>
</form>
JS
//Bootstrap Validator
$('form').validator({
// Trying to check if #login-name is valid, obviously not working!!!
if(valid.#login-name){
$('#chosen-name').prop('disabled', false);
} else{
$('#chosen-name').prop('disabled', true);
}
});
your js should be something like this:
$('form')
.validator()
.on('valid.bs.validator', function (e) {
if(e.relatedTarget.id==='login-name')
{
$('#chosen-name').prop('disabled', false);
}
})
.on('invalid.bs.validator', function (e) {
if(e.relatedTarget.id==='login-name')
{
$('#chosen-name').prop('disabled', true);
}
})
Since it uses the Constraint Validation API you can use
//Bootstrap Validator
$('form').validator().on('validated.bs.validator', function(e){
var target = e.relatedTarget;
if (target.id == 'login-name'){
$('#chosen-name').prop('disabled', !target.checkValidity());
}
})
Demo at http://codepen.io/gpetrioli/pen/MaGJzL?editors=001

Google spreadsheet website form jQuery script block the sending of

I have my form in html. I copied action, entry keys and hidden inputs from orginal Google Form.
<form id="Gform" role="form" action="https://docs.google.com/forms/d/MY-FORM-KEY/formResponse" method="POST" target="_self" onsubmit="">
<input type="text" pattern="^[a-zA-Z][a-zA-ZążźćśęółbńĄŻŹĆŃŚĘÓŁ ]{4,40}$" name="entry.1028663680" value="" id="entry.1028663680" dir="auto" title="What is Your city" class="form-control" placeholder="City" required>
<input type="text" pattern="^[a-zA-Z][a-zA-ZążźćśęółbńĄŻŹĆŃŚĘÓŁ ]{5,40}$" name="entry.1220908348" value="" id="entry.1220908348" dir="auto" title="Your complete name" class="form-control" placeholder="Your name" required>
<input type="tel" name="entry.623688995" value="" id="entry.623688995" dir="auto" title="" class="form-control" placeholder="phone" required>
<input type="email" name="entry.1564973803" value="" id="entry.1564973803" dir="auto" title="" class="form-control" placeholder="email" required>
<input type="hidden" name="entry.383122401" value="WEBSITE" id="entry.383122401" dir="auto" title="" class="form-control" placeholder="E-mail" required>
<input type="hidden" name="draftResponse" value="[,,"-9139933475238999509"]
">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fbzx" value="-9139933475238999509">
<button type="submit" name="submit" id="sendData" class="btn btn-default">Submit</button>
</form>
I have te jQuery script, which display confirm:
<script type="text/javascript">
function sendContactForm(){
$("#Gform").fadeOut();
$("#form-container").append('<p class="confirmer">Thanks!<br>Your email was sent.</p>');
};
$('#Gform').submit(function () {
sendContactForm();
return false;
});
</script>
When i delete this script, form is sending, and save to google, but after click submit, I am redirecting to google "Thank You" page. I want to no redirect and display confirm just like in script. How to fix this problem ?
try to use AJAX to acomplish your task, when you will use asynchronous function, there won't be reloading page and you will send data behind the scene. In data object enter all input values, in done() and fail() functions define what to do when you recieve response. Good Luck:)
$('#formID').submit(function(e){
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/1PrgHQALlz0WrvwjhGpLrtIgD5aQ1x-8HrOubkxTLNKs/formResponse",
type: "POST",
data: {
'entry.111': $('#entry_111').val(),
'entry.222': $('#entry_222').val(),
// all data from form
}
}).done(function(data){
yourAction(data);
}).fail(function(data){
failAction(data);
});
});
Comment the return false in the code above:
$('#Gform').submit(function () {
sendContactForm();
//return false;
});
Or just delete this line.
What this is script is doing is: subscribing to the submit event and canceling it.
Do you want to do something else?

Submit 2 forms at once

I want to submit both forms after click 2nd form's submit button.
The hardest part is that action is pointing to a php file with which send an e-mail to the client. I do not want to get 2 e-mails.
Both form data should reach that php file at the same time.
this is 1st form:
<form class="generalForm" id="form1" action="reservationSend.php" method="post">
<input id="datepicker-example3" type="text" name="datepicker-example3" value="Check In">
<input id="datepicker-example2" type="text" name="check_out" value="Choose Out">
<select name="RoomType">
<option selected="selected" value="0">Room Type</option>
<option value="Deluxe">Deluxe</option>
<option value="Family">Executive</option>
<option value="Conference">Conference</option>
</select>
</form>
This is the second form:
<form id="form2" class="generalForm" method="post" action="reservationSend.php" onsubmit="return submitForm()">
<input type="text" name="name" placeholder="Your Name" />
<input type="text" name="email" placeholder="Your email" />
<input type="text" name="tp" placeholder="Your Phone Number" />
<input type="text" name="Country" placeholder="Your Country" />
<textarea name="message" placeholder="Your Message"></textarea>
<input type="submit" name="submit" value="submit">
</form>
My javascript, myjscript.js:
function submitForm() {
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
Example submitting a form with AJAX & jQuery.
$('#formID')
.on('submit', function(e){
e.preventDefault(); //disable default submit action
var postData = {
'name' : $('input[name="name"]').val(),
'email' : $('input[name="email"]').val()
//etcetera
};
$.post(
'reservationSend.php',
postData,
callBack(returnData){
doStuffWith(returnData);
//add callback functionality
},
'json' //or any other datatype. In this case postData is a JS object, which gets submitted as JSON string
);
//You could even trigger the submission of another form here:
$('#otherForm')
.trigger('submit');
//This will trigger the submission of #otherForm
});
$('#otherForm')
.on('submit', function(e){
e.preventDefault();
//logic for form submission.
});
You can find documentation on the jQuery AJAX methods here. You'll also find serialize() and serializeArray() there. 2 Methods which can turn a form into a JSON string.

Categories

Resources