Note that there are some explanatory texts on larger screens.

plurals
  1. POValidating form data Javascript
    primarykey
    data
    text
    <p>So I am trying to set up form validation for two forms I have on a page, only one of which is visible at a time. While one form is visible (display = 'inline') the other form is hidden (display = 'none'). </p> <p>I am hooking into the forms 'submit' event and returning 'false' so that I can validate the form fields before submitting the form manually.</p> <p>The issue I run into is when I try to make the code modular, i.e. trying to set up the form behavior on both forms using common methods. When I try to do that I cannot get the form to not submit upon the click of the submit button. However, when I set up both forms individualy (duplicate methods that do the exact same thing, just using different DOM objects) I can get the functionality to work. </p> <p>Below is my attempt to loop through two arrays that create the DOM objects within the method as they are passed in:</p> <pre><code>if($('#payment_wrapper').length &gt; 0){ var form_elements = [['#nr_form', '#nr_submit_button', '#nr_notes', '#nr_amount'],['#rec_form', '#rec_submit_button', '#rec_notes', '#nr_amount']]; for (var i = 0; i &lt; 2; i++){ setupForms(form_elements[i]); } } function setupForms(arr){ $(arr[0]).submit(function(event) { (arr[1]).prop('disabled', true); validateForm(arr[0], arr[1], arr[2], arr[3]); return false; }); } function validateForm(form, button, notes, amount){ var err = false; var note = $(button).val().length var payment = $(amount).val(); if(note &gt; 150){ alert("note is greater than 150"); $('.payment_errors').text("It seems that your note is too long. Please make sure it is 150 characters of less") $(button).prop('disabled', false); err = true; } else if (!validateAmount(payment, button)){ err = true; } else if ( err == false){ $(form).get(0).submit(); } } function validateAmount(payment, submit_button){ var match = payment.match(/^[0-9]+\.[0-9]{2}/) if (payment.length == 0) { $('.payment_errors').text("You must enter a valid amount before submitting") $(submit_button).prop('disabled', false); return false; } else if (!match) { $('.payment_errors').text("Hmmmm, something is wrong with your payment amount. Make sure your amount is in the proper format") $(submit_button).prop('disabled', false); return false; } else { return true; } } </code></pre> <p>Any help would be much appreciated. Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload