简体   繁体   中英

jQuery form validation issue

I am trying to validate a series of form input fields and text area elements; using a jquery function attached to the submit event of a form. The elements are a mix of dynamically created rows of a table and one existing row of the table- from which users can add additional rows. Ideally, I would like to prevent the form submission completely if there are empty input fields or text areas on any of the rows. In a perfect world, these would then also be coloured red to indicate which ones are missing data. This is where I have gotten so far without much luck.

<button type="submit" id="create_course" name="create_course" value="sent"><img title = "click to save your newly creatde course!" id = "button_img" src="../images/red_button.png"><p id = "red_button_title"><span>Create</span></button>

                           <div id="table_wrapper">
                              <table  id="table1">
                                <thead>
                                  <tr >
                                    <th>Unit code</th>
                                     <th>Description</th>
                                      <th>Delete unit</th>
                                       <th>Add new unit</th>
                                  </tr>
                                </thead>
                                <tbody></tbody>
                               </table>
                             </div>   

                              <div id="table_wrapper2">
                              <table id="table2">
                              <thead></thead>
                              <tbody>

                                 <tr>
                                  <td><input  class = "unit <?php echo $class;?>" type = "text" name = "unit_code[]" value = "<?php echo @$_POST['unit_code'][0]?>"></td>
                                   <td><textarea cols = "10" rows = "2" id="unit_description" class="unit_description <?php echo $class;?>" name = "unit_description[]"><?php echo @$_POST['unit_description'][0]?></textarea></td>
                                    <td><img  title = "remove unit" class = "remove_row" src = "../images/exit.png"> </td>
                                     <td><img title = "add more units" class = "add_row" src = "../images/add-resource.png"></td>
                                 </tr>
                                </tbody>
                             </table>
                            </div> <!-- end of table wrapper  -->

$(document).ready(function() 
{


$(document).on('click' ,'.add_row', function() 
{

    $('#table2 > tbody:last-child').append("<tr><td><input class = 'unit <?php echo $class;?>' type = 'text' name = 'unit_code[]' value =''></td>" +
                              "<td><textarea class= 'unit_description <?php echo $class;?>' cols = '10' rows = '2'  name = 'unit_description[]'></textarea></td>" +
                              "<td><img  title = 'remove unit' class = 'remove_row' src = '../images/exit.png'></td>" +
                              "<td><img title = 'add more units' class = 'add_row' src = '../images/add-resource.png'></td></tr>");

});


$(document).on('click' ,'.remove_row', function()
{
  //place a check here that it is not the last of this element otherwise the user will not have any other way to add students if they accidentally remove the last one
  var n = $( "#table2 tr" ).length;
  alert('there are' + n + 'rows');
   if(n <2)
   {
     alert('You cannot delete this row , please leave the content blank if you do not wish to enter any data');

   }
   else
   {
      $(this ).parents('tr').remove();
  }
 });

$('textarea').each(function(){
        $(this).val($(this).val().trim());
    }
);


$(document).on('submit','#submit_design', function(e)
{

 var unitCode;
 var unitDescription;
 var validate=true;

  $("#table2 tr").each(function() 
   {

     // this represents the row
     $("td > *", this).each(function() 
     {

       function processRow () {

        if(this.nodeName == "INPUT") 
        {
         console.log('input node called');
           unitCode = $(this).val();
         }
        if(this.nodeName == "TEXTAREA")
        {
         console.log('textare node called');
           unitDescription = $(this).val();  
        }

        }

        processRow();

        if(unitCode == null && unitDescription != null)   
        {
          alert('validatioj area called');
          validate = false;
        }

        if(unitCode != null && unitDescription == null)
        {

           alert('validatioj area called');
          validate = false;
        }

      });
   });

  alert(validate);
    if(!validate)
     {
      alert('you must provide both a unit code and a description code for every entry, please ammend');

     }
 });//end of validate form function   

});  //end of javascript on document.ready

Key here for me was to understand how preventDefault() works and to ensure good use was made of lexical scope and a flag. What was confusing was that setting the event of a form submission to trigger the function did not work, but the calling of the function via the click of the submit button did the trick. Not really sure why but it seems to be working here is the amended javascript (jquery) code:

   $('#create_course').click(function(e)
 {     

      validate = true;                                 
    $("#table2 tr").each(function() 
     {
        var unitCode = null;
         var unitDescription = null;


          // this represents the row
          $("td > *", this).each(function() 
           {               
                if(this.nodeName == "INPUT") 
                {
                 unitCode = $(this).val();
                }

               if(this.nodeName == "TEXTAREA")
                {
                  unitDescription = $(this).val();       
                }                   
           });

            if(unitCode === '' || unitDescription === '')
            {
              alert('Please ensure that you enter a unit code and description for each entry');


             validate = false;
            }

       if(!validate)
       {
        e.preventDefault();
       }
     });
 }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM