jQuery Function and Javascript Functions Not Working Together - javascript

I am trying to run a jQuery function with some other Javascript functions. I suppose I am not understanding the syntax correctly. I have a colorbox that opens on page load with a form in it. When the form is submitted I am trying to have a validation run first and then if successful run a jQuery function that closes the Colorbox and validates the parent window. This is where I'm at now (by the way, I've been all around the circle with this. I've been able to get the jQuery function to work, I've gotten the validation functions to work but I've never gotten them to work together. I apologize if I've gotten way off base but I think I've drifted away since I was trying some new things):
Just tried this:
window.echeck(str) = function {
var at="#"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at,(lat+1))!=-1){
alert("Invalid E-mail ID")
return false
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot,(lat+2))==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(" ")!=-1){
alert("Invalid E-mail ID")
return false
}
return true
}
window.ValidateForm() = function{
var emailID=document.MailingList.emailaddress
if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (echeck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}
$(document).ready(function() {
$('#submitbutton').live('click', function(e) {
ValidateForm();
parent.$.fn.colorbox.close();
parent.location.href = "/SearchResults.asp?Cat=1854";
});
});
I didn't execute any of the functions.
When I remove ValidateForm(); from the jQuery and when I put the syntax of the javascript functions back to function ValidateForm(); instead of window.ValidateForm = function() the jQuery works but of course the other javascript functions do not.

an I not create nested functions inside of the main jQuery function
You can't reference functions from outside the $(document).ready(function() { }); block, because it's a private scope. You need to either define one of the functions outside of the scope, so that it's accessible --
$(document).ready(function() {
// define in the global scope (window) so that it's accessible anywhere
window.ValidateForm = function() { ... }
});
// this works
ValidateForm();
or wire up your events by using on --
$(document).ready(function() {
$("#theform").on("submit", ValidateForm);
});

Related

Load file in new window with event listener on form submission while keeping other form validations valid

I have a web form that has a sales force "Web-To-Lead" form action. The end goal is to have the form submit like normal while also loading pdf into a new page.
I have two validations set up for certain form items.
The first one is a captcha validation which looks like so:
var allow_submit = false
function captcha_filled () {
allow_submit = true;
}
function captcha_expired () {
allow_submit = false
}
function check_captcha_filled (e) {
console.log('verify captcha')
if (!allow_submit) {
alert('ERROR: Please verify you are human by filling out the captcha')
return false
}
captcha_expired()
return true
}
(This works as expected.)
The second validation I have is for an input to be :checked in order for the form to submit. That code is as follows:
function fnSubmit() {
if($("input:checkbox[id='chk']").is(":checked") == false){
alert("You must agree to collect and use your personal information.");
return false;
}
}
(This also works as expected.)
The problem comes with trying to integrate my pdf_Download() function while maintaining those validations. Because the form action is already reserved for the web-to-lead, I decided to use an onclick EventListener that generates a new window to open with the desired location. The location uses a <?=$_REQUEST in PHP.
Below is a minimal example of the form and the js I have attempted so far to make this work.
<form action="web-to-lead" method="POST" onSubmit="return fnSubmit() & check_captcha_filled() & pdf_Download()">
<button class="def_btn bluest" name="submit">Contact</button>
<script>
function pdf_Download(e) {
if($("input:checkbox[id='chk']").is(":checked") == false || !allow_submit == false) {
e.preventDefault()
return false
} else {
document.querySelectorAll('button.bluest').addEventListener("click").window.open('<?=$_REQUEST['bf_file']?>');
return true
}
}
</script>
If something is unclear please let me know.
I believe it will work with this
If it doesn't work please add screenshot devtools I will correct the answer
<form action="web-to-lead" method="POST" onSubmit="fnSubmit() && check_captcha_filled() && pdf_Download()">
<button class="def_btn bluest" name="submit">Contact</button>
<script>
function pdf_Download(e) {
if($("input:checkbox[id='chk']").is(":checked") == false || !allow_submit == false) {
e.preventDefault()
return false
} else {
window.open("<?=$_REQUEST['bf_file']?>");
return true
}
}
</script>

How to return a value from a jQuery event function to the parent function?

I have a jQuery event inside a JavaScript function. I've already read that you cannot access the inner function. However, I would like to know how to adjust my code so that the parent function returns true or false depending on the jQuery function.
function validate() {
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
if (input == "") {
return false;
}
});
if(onclickfunction() == true){
return true;
}
else{
return false
}
}
validate();
Or can you recommend a different approach?
Not sure what this code is supposed to do, because calling validate only creates the event listener without actually executing it. But what you can do is to prevent the default action when you need, which is how validation is usually implemented:
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
yourSecondFunction(input !== "");
});
function yourSecondFunction(inputIsValid) {
// Do your magic here
}

Prevent a form from being submitted javascript why is there an obvious false statement returning true?

<script>
function someFunc() {
if (1==2) {
return true;
} else {
alert("Not submitting");
return false;
}
}
</script>
This is from stackoverflow here
prevent form submission (javascript)
I want to know what the purpose of the obvious false statement 1==2 returns true is for?
In general, to stop a form from submitting you would need to do two things:
Place an "onsubmit" event on the form tag
define the event handler in javascript and return false in that function
So, basically, in HTML you would need:
<form ... onsubmit="return someFunc()">
And in the javascript code you would need:
function someFunc() {
return false;
}
The part with 1 == 2 its for developing purposes only i would imagine, just a mechanism of making the forms to never submit.
When moving on from the developing environment this should be done in a more clever configurable way.
You might as well have a function like this:
function someFunc() {
if (1 > 0) {
return true;
} else {
alert("Not submitting");
return false;
}
}
That validation is only meant to always stop the from from submitting.
Or, a function like this:
function someFunc() {
alert("Not submitting");
return false;
}

Javascript Form Validate

I am trying to validate input on an HTML form. I am trying to use one script to validate various forms that have several similar elements. All in all there are about 15 different fields but I am only putting 3. Below works on the form that has all of the elements but fails on any form that does not have a specific field.
if (form.name.value == ""){ // Check if blank
alert( "\nEnter a name." );
form.name.focus();
return false; // Stop the form processing.
}
else if ( !/^\w{10}$/.test( form.phone.value )) { // Check for phone
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
else{
return true; // Submit!
Since this only works if all are present what i want to do is validate only if it exists. I have tried nesting the validation under a statement that should check for the element before trying to validate it and if the element doesn't exist it should move on to the next.
if (document.forms[0].name){ //does field exist?
if (form.name.value === ""){
alert( "\nEnter a name." );
form.name.focus();
return false; // Stop the form processing.
}
else{
return true; //field ok move on.
}
}
else if (document.forms[0].phone){
if ( !/^\w{10}$/.test( form.phone.value )) { user
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
else{
return true; //field ok move on.
}
}
else{
return true; // Submit!
}
Any help help would be appreciated!
At present you are checking that (document.forms[0].name) is available and then if this is dead it check if (document.forms[0].phone) is true and then...... and then if none are true it resorts to the 'else' and returns are true. The use of if else means that you only bother with anything after if this part has failed.
You could try.
if (document.forms[0].name) {
if ( !/^\w{10}$/.test( form.phone.value )) { user
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
}
if (document.forms[0].blah) {
do stuff...
if fail
return false;
}
return true;
As the function is going to return as true anyway, you don't need to state return true anywhere else (also this will stop the process as it has returned and stopped). The only reason to stop the process if things have gone wrong.. hence return false;
If you just need to validate a form, you don't need to write javascript nowadays. You can use html5 forms. Even if you have to support browser without this feature, you can put the webshims lib at your page to enable it.

Javascript: how to bring focus to an element, and show a warning message

Preface, I really don't know javascript at all.
I am trying to validate the email address of a form. If validation fails, I would like to focus on the invalid email field, and show a warning message. The below code properly returns true or false if the "focusElement" line is removed. However, it always returns true with that line included (presumably because the line is invalid and the code does not execute. Is there a proper/simple way of focusing on this element and showing the message?
function validateForm(formElement)
{
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailPattern.test(formElement.tfEmail.value))
{
return true;
}
else
{
focusElement(formElement.tfEmail,'Please enter a valid e-mail address.');
return false;
}
}
Use .focus() and alert()
...
else
{
alert('Please enter a valid e-mail address.');
formElement.tfEmail.focus();
return false;
}
If you would like the functionality to be in a separate function like your example:
...
else
{
focusElement(formElement.tfEmail, 'Please enter a valid e-mail address.');
return false;
}
function focusElement(obj, msg)
{
alert(msg);
obj.focus();
}
function focusElement(el, message) {
alert(message);
el.focus();
}
Try:
alert("Ur err msg");
document.getElementById("yourEmailFieldId").focus();
You should try use jQuery and jQuery Validate for this task.
jQuery is the most used JavaScript framework, it can simplify a lot of any tasks in JavaScript.
jQuery Validate is a very used plugin for validation, based on jQuery.

Categories