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

    • Ombre Mountains Quilt Pattern by BusyHandsQuilts.com is a modern design that creates an ombre effect. The pattern includes all the sizes from Baby to King. #busyhandspatterns #ombremountainsquilt #ombrequilt #modernquilting

    • Leading Edge Quilt Pattern PDF Download - Etsy

    • Homecoming Quilt- My Peppered Cotton version & tester quilts! – Lo & Behold Stitchery

    • Homecoming Quilt- My Peppered Cotton version & tester quilts! – Lo & Behold Stitchery

    • On the Edge is a quick and fun modern quilt pattern with a lot of custom design possibilities! This PDF pattern includes directions for making a twin-size quilt (72 x 96), a throw-size quilt (56 x 64), a baby size (38.5 x 44), and a pillow/mini quilt (18 x 18). See the Instagram hashtag

    • Follow Me on Pinterest