jquery form validation script doesn't work - javascript

Hello there i have a problem calling jquery script to work. I have an index.html file. Where i include jquery like this: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> And my file with jquery script like this:<script type="text/javascript" src="js/error.handler.js"></script>
Then when special button is clicked, AJAX function loads regForm.html file into body of index.html there i have registration form like this:
<form name="regForm" id="regForm"action= "save_user.php" method="post">
******
<ul id ="inputForms">
<li id="l11"><input type = "text" id="login" name="login" size="15" maxlength="15" /></li>
</ul>
******
<div id="regButContainer"> <input type="submit" id="regButton2" value="Register Now" name="submit"></div></form>
I try to make verification of login input field with this script:
$(function(){
$( "#regForm" ).submit(function( event ) {
var errors = false;
if($('#login').value() == ""){
alert("lLOGIN CANNOT BE EMPTY!");
errors = true;
}
if (errors==true) {
return false;
}
});});
But when submit button is clicked script is not working so it ends up triggering save_user.php file to work. When i use html's onsubmit function and use standard javascript function everything works. But there is fancy things i want to do with jquery so i switched to it and now i'm in front of a brick wall. Can anyone explain me why my script refuses to work?

You need to place your $('#regForm).submit( ) function after the form is loaded by the AJAX.
Assuming you're using $.load( ) to do this, it should look something similar to this:
$('#form_container').load('regForm.html', function() {
$( "#regForm" ).submit(function( event ) {
var errors = false;
if($('#login').val() == ""){
alert("lLOGIN CANNOT BE EMPTY!");
errors = true;
}
if (errors==true) {
return false;
}
});
});
The reason for this is because the form isn't loaded at the time your add the submit event.

Just add the event.preventDefault(); in any case you want to stop the form from submiting.
Also I believe that your problem is that you should have $('#login').val() instead of $('#login').value(). normally your script should work without preventDefault();
http://jsfiddle.net/cra5L/
$( "#regForm" ).submit(function( event ) {
if($('#login').val() == ""){
event.preventDefault();
alert("lLOGIN CANNOT BE EMPTY!");
errors = true;
}

change
$('#login').value()
to
$('#login').val()

Related

jQuery submit() with spin.js is preventing form from submitting?

I have a form that submits just fine, but when I add jQuery code to show a loading div using spin.js everything stops working.
<form id="search_form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<!-- Form inputs here -->
...
<input id="exam_search" type="submit" name="submit" value="Search" />
Once I add the following code the form stops submitting and nothing happens. The loading div shows for a brief moment and then goes away like expected, but it seems like the form isn't actually submitting anymore.
var opts = // Array of options
var spinner = null;
$("#search_form").submit(function() {
spinner_div = document.getElementById('spinner');
if(spinner == null) {
spinner = new Spinner(opts).spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
} else {
spinner.spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
}
});
If I change all of that code in the submit event to this:
$("#search_form").submit(function() {
alert ("form submitted");
});
It shows the alert and then returns the results of the form submission just fine.
What am I doing wrong here?
EDIT
I saw in the jQuery docs for submit() that I shouldn't use the name "submit" on the input field. I tried changing that as well with no luck.
Well I'm not sure why but simply doing this worked:
$("#search_form").submit(function() {
var spinner_div = document.getElementById('spinner');
var spinner = new Spinner(opts);
spinner.spin(spinner_div);
});

Prevent Form from Submitting if there are Errors

Before I get into the problem details, I still need to tell you about this form I am creating. I have a Registration form and once the user submits the form by clicking the Submit button, it will NOT go directly to a Successfully Registered page. The user will be seeing a Confirmation page prior to that. In this page, the user will see all the data he inputted for him to review. Below it are the Confirm button and the Return button (if user still likes/needs to edit his details, it will then show the form for him to edit once this button is clicked). But here's the thing, the Registration form page and the Confirmation page are in just the same page. What I did is that when the user submits the form, it will hide some elements including the Submit button and then just show the details he inputted. When the user clicks the Return button on the Confirmation page, it will just then show again the hidden fields so the user can edit his details.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working. I am using bootstrap for my form so when there are errors, the input fields' borders would turn red and would obtain a class has-error. Here's what I did:
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
But again, it is not working. I also googled some jQueries like the .valid() and .validate() functions but I'm not really sure about it and also didn't work for me.
I also did this code where the Submit button should disable when required fields are still empty. And it is perfectly working:
$('#submit').attr('disabled',true);
$('input[id^="account"]').keyup(function() {
if(($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0)) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
I hope you understand my problem. I will make it clearer if this confuses you.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working.
When is it checking for errors? It needs to disable the submit button at the same time it is checking for errors. Your code doesn't work because there's no event telling it WHEN to execute. WHEN do you want submit button to be disabled?
Do you want it triggered when the field is validated or when the form is submitted?
You can't really tie it to the submit button unless you want to click it first to validate the form fields, and then again to submit validated fields. Then you'll need to figure out how to tell it that it's been validated like by a class, maybe? Only accept inputs that hasClass('valid')?
below are the changes
$(".form-group").find("td").each(function() {
if($(this).hasClass('has-error')) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
Try the following
$('#submit').click(function(){
var error = false;
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
error = true;
return false; //break out of .each
}
});
return !error;
});
You can achieve this by maintaining 2 sections.
1. Form section
<form id="form1">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="button" id="confirm" value="Confirm" />
</form>
2. Confirm section
<div id="disp_data" style="display: none;">
<lable>Name: <span id="name_val"></span></lable>
<lable>Email: <span id="email_val"></span></lable>
<input type="button" id="return" value="Return" />
<input type="button" id="submit" value="Submit" />
</div>
You have to submit the form by using js submit method on validating the form in confirm section (When the user clicks on submit button)
$("#submit").click(function(){
var error_cnt = false;
if($("#name").val() == '') {
error_cnt = true;
alert("Enter Name");
}
if($("#email").val() == '') {
error_cnt = true;
alert("Enter Email");
}
if(error_cnt == false) {
$("#form1").submit();
} else {
$("#disp_data").hide();
$("#form1").show();
}
Demo
You have to prevent the form from sumition by return back a boolean false so that it will stop the execution.
$('#submit').click(function(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
if(!ret) return false;
});
If you want to disable the submit button in case of any error you need to monitor the changes of each input fields. so better to give a class name to all those input fields like commonClass
then
function validation_check(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
return ret;
}
$("#submit").prop("disabled",true)
$(".commonClass").change(function(){
if(validation_check()){
$("#submit").prop("disabled",false)
}
else {
$("#submit").prop("disabled",true)
}
});
please use onsubmit attribute in the form element and write a javascript function to return false when there is any error. I've added fiddle you can try.
HTML FORM
<form action="" method="" onsubmit="return dosubmit();">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="submit" value="Submit" />
</form>
JAVASCRIPT
function dosubmit() {
if(false) { //Check for errors, if there are errors return false. This will prevent th form being submitted.
return false;
} else {
return true;
}
}
Let me know if this fixes your issue.

jQuery - doesnt submit data on enter

I am trying to work with a chatroom and some users would like a feature to submit on enter.
I current have this code:
Form html:
<form id="send-message-area" name="send-message-area" method="post" action="">
<textarea id="sendie" name="sendie" maxlength = '255'></textarea>
<input type="submit" name="sendieButton" id="sendieButton" value="Send" />
</form>
jQuery:
$(document).ready(function(){
$("textarea").keyup(function(event){
if(event.keyCode == 13){
//$("form").submit();
$("form").trigger("submit");
}
});
});
However when hitting enter it does indeed submit, however it doesn't send any data with it.
It works just fine when pressing the submit button.
I already tried $("form").submit(); but it does the exact same.
EDIT:
I think the problem lays in my PHP.
if(isset($_POST['sendieButton'])){
$fromID = $brugernavn;
$fromMsg = $_POST['sendie'];
sendMsg($fromID, $fromMsg);
};
However when changing to check for $_POST['send-message-area'] it doesn't work at all.
Your button value will not be submitted until you click on it. So either you trigger its click event
$(document).ready(function(){
$("textarea").keyup(function(event){
if(event.keyCode == 13){
//$("form").submit();
$("#sendieButton").trigger("click");
}
});
});
or check only textarea value isset or not in PHP
if(isset($_POST['sendie'])){
$fromID = $brugernavn;
$fromMsg = $_POST['sendie'];
sendMsg($fromID, $fromMsg);
};
You need to check for name of the textarea not the button
if (isset($_POST["sendie"])) {
$fromMsg = $_POST['sendie'];
}else{
echo "no sendie";
}

Send message from input field into database by pressing enter

i've done a web chat which the codes are:
<div id="namebox">Name: <input type="text" id="name" autofocus autocomplete="on" ></div>
<div id="msgbox" >Message: <input type="text" id="message"></div>
<div id="submitbox"><button onClick="postMessageToDB(); return false;" id="submit">Submit</button></div>
So, the message goes into the database fine by clicking the button submit, however i was wondering to ad a code to jut press enter and it will be sent, so there will be 2 options.
I am using onClick and onKeypress which it is not working.
<div id="submitbox"><button onClick="postMessageToDB(); return false;" id="submit" onkeypress="postMessageToDB(this, event); return false;">Submit</button></div>
Where the javascript is:
<script type="text/javascript">
function postMessageToDB(inputElement, event) {
if (event.keyCode == 13) {
inputElement.div.submit();
}
}
</script>
Im not using form because it was asked to be div, not form.
Really appreciate for any help.
Thank you very much
Your code provided will only work when postMessageToDB() is called... it's not listening for a keypress.
Using jQuery:
$(window).keyup(function(e) {
if( e.keyCode==13 ) {
postMessageToDB([...]);
}
}
You need to call the function, you can do this by adding an EventListener to document and then check if it's enter that was pressed.
var keyevent = (/Firefox/i.test(navigator.userAgent)) ? "keypress" : "keydown"; // fit browser
document.addEventListener(keyevent, function(e) {
if (event.keyCode == 13) {
var a = document.getElementById('name').value; //get field values
var b = document.getElementById('message').value; //get field values
postMessageToDB(inputElement, event); // as I said, not sure what this will do, but you need to get the data you want to pass first within this function.
}
});
Then, just remove the keypress checkup from you function and you should check this line, I can't see that this is going to work:
inputElement.div.submit();

HTML5 form validation without submit button

i want to validate the form inputs without an type="submit" button.
How can i do this?
I tried this ->
<script type="text/javascript">function validateForm() {
$('#form1')[0].checkValidity()
if( document.form1.vorname.value == "" )
{
return false;
}
if( document.form1.nachname.value == "" )
{
return false;
}
if( document.form1.postleitzahl.value == "" )
{
return false;
}
if( document.form1.email.value == "" )
{
return false;
}
if( document.form1.telefon_optin_Ja.value == "" )
{
return false;
}
if( document.form1.ort.value == "" )
{
return false;
}
if( document.form1.straße.value == "" )
{
return false;
}
if( document.form1.Anrede.value == "" )
{
return false;
}else {
$('#modal_absenden').modal({
backdrop: 'static',
keyboard: 'false',
})
}
}
</script>
My form name is: form1 , button -> `Absenden
The "background" of the question is: I want to validate the form inputs first, then (if all inputs ok) it should opens a modal, where u can select the redirect page (redirect yes, redirect no) then it submit the form via post to mail.php.
I hope u understand my question, if u have questions, pls ask. (My english is not so good..)
Thank you for help.
You have said about HTML5.
Then that means all you have to do is to use checkValidity() along with
<input type="text" name="name" required>
<input type="email" name="email" required placeholder="Enter a valid email address">
Here is the nice article about using HTML5 validation.
I have not used by myself. But I am glad to know a bit from your post.
http://www.the-art-of-web.com/html/html5-form-validation/
If you want to use jQuery one then go for validation.
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQuery-Validation-Plugin
You could call your validate function everytime an input changes:
$('#form1 input').change(validateForm);
Using
$("#form1 input").on('change,blur', validateForm);
function validateForm() {
// Caution : this refers to the HTMLElement
}
You shoud consider to use a jQuery form validation like library like http://formvalidator.net/ or http://jqueryvalidation.org/ or create yours.
Cheers
So I guess you want to do frontend validation with Javascript. There are wrapped library to do this. E.g., validate.js, verifyjs, and this one, ...
And you can bind the validation process on the blur event of an input
JQuery validate is a good choice with clear documentation. You just need to download the .js library and place it somewhere under your web folder, and using tag to include it. And call the .validate() function on the form you want to validate. That should be done.
$('input').on('blur', function(){
$("#myForm").validate();
});

Categories

Resources