My collection of things.

jKafer on the Net

January 12th, 2018 at 12:34 pm

Javascript – check required fields in form – return to form

PROBLEM: check required fields (more than 2) before adding items to a database – this will help curb bad data entries in your database.

I have a form that uses .ajax to write to the database and then relist all the items added. Like a shopping cart…in a way.  So I split out the validation part – it was simpler this way.

<input type=”button” class=”addtocart_button” value=”Save” title=”Save” onClick=”ckItem()” />

SOLUTION:

When the “Save” button is clicked it runs: ckItem()  –

function ckItem(){
//javascript function loaded in header
   
   $formID = "itemEntry";
   //pulls information from form that was submitted
   $category = document.forms[$formID]['category'].value;
   $genius = document.forms[$formID]['desc1'].value;

   //checks required fields for data  
   if (!$category || !$genius) {
       //if required field(s) are blank, do not add record
      alert("Category & Description are required fields");
      if (!$category) {
         document.forms[$formID]['category'].focus();  //returns cursor to this field
         return;  //stops the function
      } else if (!$genius) {
         document.forms[$formID]['desc1'].focus();  //returns cursor to this field
      }
   } else {
      //if both fields have data, it will now write the data to the database
      saveItem();
   };
}

 

Tags: ,
-

Comments are closed.

  • Pages

  • Latest Pins on Pinterest

    • Follow Me on Pinterest
  • Quilting Projects I Want to Make

    • This is Reneta's version of Elizabeth Hartman's Fancy Forest quilt. This quilt is a bit of a labour of love. It has A LOT of pieces!...

    • Flying Bird Quilt Blanket The fleece blanket features a lightweight, pill-free microfiber fleece that is not only supremely soft, but warm and cozy.

    • french braid quilt pattern | Thread: My First French Braid Quilt!

    • Follow Me on Pinterest