jQuery form submit doesn't appear to trigger if statement - javascript

I have this error but I can't see how to fix it. I've used JSLint with some results (it just tells me document isn't a global value, or the 'else clause' was not needed, etc) but no solution.
I have a form to be submitted and I need to compare that both email fields are equal. So I want a nice simple email1 == email2 script, jQuery isn't my strongest point, but I came up with this:
My form ID is "regIn", my email fields are type="email" (HTML5) and id="MailA" and id="MailB" respectively.
I have preloaded jquery 1.11.1.min.js
My jQuery code (see below why the #forgotten is still in there):
$(document).ready(function() {
$('#forgotten').click(function() {
$('#passbox').toggle(360);
return false;
});
$('#regIn').submit(function() {
// * referenced; but this isn't in the code: alert('alert1');
if ($('#MailA').val() === $('#MailB').val()) {
return true;
}
$('#errorMsg').innerHTML("Emails need to be the same!");
alert('Hello');
return false;
});
});
So - I use Alerts to see how far the script gets (i know, tacky debugging). firebug doesn't report page errors or script errors that I can see. The "alert 1" always fires on form submission, and successfully shows me the values of #MailA.val() and #MailB.val(),
But the if statement doesn't seem to fire at all. I have tried making the values variables (var d1 = $('#MailA').val() etc. ) but that doesn't change anything, the form always submits and neither the if or the else (which did surround the text below the if statement clause but JSLint said it wasn't needed so I removed it).
I have also used variations of syntax, using != and == but was also reading from JSLint that === and !== are preferred.
My HTML:
<form enctype="multipart/form-data" name="regIn" id="regIn" autocomplete="off" accept-charset="utf-8" action="#" method="post">
<div class="inputContainer">
<input type="email" value="" tabindex="31" id="MailA" name="regMailA" required>
</div>
<div id="errorMsg"></div>
<div class="inputContainer">
<input type="email" value="" id="MailB" tabindex="32" name="regMailB" required>
</div>
<div class="registerRow">
<input type="submit" class="regButton" value="Register" tabindex="34">
</div>
</form>
As I said, I've looked around for the last hour or so and I just can't see what it is.
Obviously the code is stripped down for the question, the only other aspect is that there is another piece of jQuery in the document ready function - as shown the #forgotten appears for showing / hiding an info. box, this works fine.

please note that you are using:
$('#errorMsg').innerHTML("Emails need to be the same!");
if you try to alert $('#errorMsg').innerHTML it will be undefined.
When you using JQuery selectors $('#errorMsg') JQuery will wrap the dom object with JQuery dom object that own JQuery special methods(val, html, etc), so you don't have access to the core method innerHTML, instead you should use:
$('#errorMsg').html("Emails need to be the same!");
Enjoy!

Related

onsubmit not being called on an HTML form

I have the following form as part of my webpage:
<form id="collabAccess" onsubmit="submitCollabForm()" >
<div id="row-1">
<div class="two-col" id="email"><input type="text" placeholder="Enter email addresses separated by commas"/></div>
<div id="collabSelect" class="collab two-col styled-select">
<select id="collabaccess">
<option>Can Read</option>
<option>Can Write</option>
<option>Can Read & Write </option>
<option>Administrator </option>
</select>
</div>
</div>
<div id="message">
<textarea id="personalMessage" cols="154" rows="10" placeholder="Optional: include a personal message"></textarea>
</div>
<div id="submit-wrapper"><input type="submit" value="Add Collaborators" id="addCollaborators" disabled='disabled' class="small-btn disabled"/></div>
</form>
The function submitCollabForm() is as follows:
function submitCollabForm() {
console.log('in submitCollabForm');
var valid = validateEmails();
if (valid == false) {
var email = document.getElementById('email');
email.addClass('error');
}
}
where validateEmails() is just another js function for validating that the email addresses int he form have the correct format.
However, it looks like onsubmit is not being called at all. Even if I change things to onsubmit="console.log('xyz'), no console statement is being output. I've also checked for javascript errors in the console, but I am getting nothing.
Is there any reason why onsubmit is not working properly?
Your validation function needs to return false to stop the form from submitting. It's better to have
onsubmit="return submitCollabForm()"
See With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"? for details.
The onsubmit handler is not called, because the form cannot be submitted by any normal means, i.e. the submit event cannot be caused. There is only one submit control, and it is declared as disabled.
if you feel all code is correct still it's not working then,
Simple steps to do,
1) create one script tag in the same page where your form is, create one function and set one alert and test it. If it is working then try following steps.
2) Try to check the path of your javascript file.
3) if path is correct, then change the name of your javascript function sometimes your name tag conflicts with your function name, and submit points to it, so your call is not reaching at your function. It happened with me. so I posted it here, hope it will be helpful to someone.

Validating user input using javascript

I'm trying to validate what a user enters into a texbox on the client-side, using javascript. I have also added a span close to my input tag like so,
<div>
<label for="fname">First Name*</label>
<input id="fname" name="fname" maxlength="30" type="text" /><span style="display:none;" id="fnameerror" name="fnameerror">*Please enter your firstname</span>
</div>
Here's the javascript code snippet validating the input,
if(document.getElementById('fname').value.length==0){
msg='Please enter your first name';
document.getElementById('fnameerror').style.display='inline';
document.getElementById('fnameerror').style.color='red';
valid=false;
}
What I want to achieve now is,
1) The textbox with the error should gain focus.
2) After the error message is displayed and the user enters a valid data, the error message should disappear.
How do I achieve this. I'm fairly new to javascript. Thanks.
Change your JS code:
document.getElementById('fname').onkeyup = function() {
if(document.getElementById('fname').value.length==0){
msg='Please enter your first name';
document.getElementById('fnameerror').style.display='inline';
document.getElementById('fnameerror').style.color='red';
valid=false;
document.getElementById('fname').focus();
} else {
valid=true;
document.getElementById('fnameerror').style.display='none';
}
}
Fiddle.
If you've read about HTML5, it allows you to add form validation as attribute fields directly instead of having to write code for it. It also presents things neatly. Have a look. This might help:
http://diveintohtml5.info/forms.html
I will suggest to use Jquery validator. Of course you need to include jquery,and jquery plugin, but you do not need time to write validation from the scratch only to implement what exist.

How to validate form fields in a facebox?

I need to validate my form fields displayed in facebox.
The problem is that i am unable to get the values of the fields by using javascript.
for ex: document.form.field_name.value doesnt return its value.
Code sample :
<script type="text/javascript">
function validate()
{
if (document.form1.field.value=='')
{
alert ("Field cannot be left blank");
}
}
</script>
<form name="form1" onsubmit="return validate()">
<input type="text" name="field" />
</form>
A way to do this would be to pass the value directly from the form to the validation code.
<form name="form" id="form" onsubmit="return validate(this.field.value)">
<input type="text" id="field" />
</form>
Or you could even use a text box without the form using:
<input type="text" id="field"
onkeydown="if (event.keyCode == 13) return validate(this.value)" />
Update the script to allow for the new value parameter:
<script type="text/javascript">
function validate(val) {
if (val.length < 1)
{
alert ("field cannot be left blank");
return false; //to stop the default action of submitting the form
} else {
alert ("Value: "+val);
return true; //allow to submit the page
}
}
</script>
This is actually a pretty easy and simple validation, but don't forget to set the return action based on whether you want the system to proceed with the submit or not.
I'm not sure where your pulling your page from whether from a remote html address or a locally stored div. So I'm not sure why your solution of pulling the value from the DOM does not work. I generally have no problems using jquery to get and set the values from the different fields in facebox windows.
NOTE: you have to be careful where you place your scripts. It depends on your application but sometimes you may want to place the script in the root document instead of the facebox page because if you load a remote facebox div you have a scope change and may need to refer to parent.document to access parent fields when the script is embedded in the remote facebox div.
Facebox copies the chunk of DOM displayed, effectively creating elements with duplicate ids. This is not allowed by HTML standard. Your javascript goes bonkers looking for a single element uniquely identified by its id, yet it finds 2 of them...
This is a huge bug in Facebox. Any code in a facebox should not have ids. All your bindings should be renewed when the facebox is revealed.

Jquery / Html form

reaching a point of confusion
I am creating a couple of input elements and a button to search.
From using HTML previously, I am lead to believe that i should create a and contain my elements and
But the data is not to be sent anywhere apart from to the javascript to show the correct place in the google map.
I've managed to confuse myself; do i need a element to contain and s ?
The problem is when i press a whether it be a test or a search button the page reloads.
I do not want the page to reload. The only way for me not to get this to happen is by removing element, this does not feel right, I am concerned with using good practice if possible.
This is my code:
<form id="maps_form">
<fieldset id="search_maps">
<label for="marker">Search Shop: </label>
<input name="searchName" id="searchName" type="text" placeholder="Enter Shop Name">
</fieldset>
<fieldset id="map_buttons">
<button id="test"> test</button>
<button id="searchSomething">Search</button>
</fieldset>
</form>
I feel like, whilst am learning this javascript, dipping into jquery and learning xml, I am forgetting the basics of html :s is this normally to lose touch whilst learning new languages?
The page will reload if your your click/submit handler doesn't return false. So page will refresh if:
If your Javascript listener isn't registered correctly
Your Javascript handler returns true
Your Javascript handler causes an error (check dev console for errors)
$("#maps_form").submit(function () {
// do stuff
return false; // Don't submit the form
});
Never do that! Wouldn't prevent go to next page if too many action after return false.
$("#maps_form").submit(function () {
// do stuff
return false; // Don't submit the form
});
This is correct form:
$("#maps_form").submit(function (event) {
event.preventDefault();
...
});

Using Javascript to submit forms

EDIT: For some reason if I change the input into an , the submit code works fine. Ok, this works, I'll just style the a tag to look like an input tag in css.
I am using a jQuery function to submit a form when a certain button is pressed, however this seems to have no effect on the form.
My code is as follows:
HTML:
<form id="loginForm" action="" method="POST">
<input class="loginInput" type="hidden" name="action" value="login">
<input id="step1a" class="loginInput" type="text" name="username">
<input id="step2a" class="loginInput" type="password" name="password" style="display:none;">
<input id="step1b" class="loginSubmit" onclick="loginProceed();" type="button" name="submit" value="Proceed" title="Proceed" />
<input id="step2b" class="loginSubmit" onclick="submitlogin();" type="button" value="Validate" title="Validate" style="display:none;" />
</form>
Javascript:
function submitlogin()
{
$("#loginForm").submit();
}
function loginProceed()
{
$("#step1a").fadeOut("slow",function(){
$("#step2a").fadeIn("slow", function(){
$("#step2a").focus();
});
});
$("#step1b").fadeOut("slow",function(){
$("#step2b").fadeIn("slow");
});
$("#step1c").fadeOut("slow",function(){
$("#step2c").fadeIn("slow");
});
}
However, when I press the button, absolutely nothing occurs.
PS. This function may seem meaningless since I can just use a input type="submit" but I originally intended this to have some more functionality, I stripped the function to its bare bones for testing purposes.
Try to use another name for input with name="submit". Without this it works fine for me.
You need to specify one form.
$("#loginForm").submit();
EDIT: Additional information added to question. You appear to be calling the wrong function. The submit button that is not display:none calls loginProceed() not submitlogin().
Also, if the functions are defined within jQuery's ready() function, they will be out of scope unless you define them as global.
Live example: http://jsfiddle.net/eSeuH/
Updated example: http://jsfiddle.net/eSeuH/2/
If the code you noted in the comment runs before the DOM is loaded, it will not work. You need to ensure that it does not run until the DOM has loaded (or at least the element it references has loaded).
$(document).ready(function() {
$("#loginForm").submit(function() { alert("clicked"); });
});
Additionally, your action attribute in your form tag is empty. What do you expect to happen when the form is submitted?
Try look in to Firefox debug console. Maybe you have errors in javascripts???
Because even if action is empty, all works.
For some reason if I change the input into an , the submit code works fine. Ok, this works, I'll just style the a tag to look like an input tag in css.
There's no jquery 'submit' method (not for ajax, at least): http://api.jquery.com/category/ajax/
You probably want to invoke form's submit method:
$("#loginForm")[0].submit();
Remember, jquery selector always returns array.
edit
'submit' will actually bind handler to submit event, not submit form:
http://api.jquery.com/submit/

Categories

Resources