htmljquerydynamicform

Dynamically generated html form don't allow jQuery bind("submit") method


I have the following dynamically generated form in which some checkboxes have hidden input fields which shown up when the user check that specific checkbox. I need few requirements here:

  1. To check at least one check box before saving the form
  2. To check if the hidden input has been shown, then it should not be empty
  3. If the user click on add new input box using the "+" icon the newly appended input field must also be filled

If all the above requirements fulfilled, then the user may be able to submit the form.

   <form method="post" action="fakeUrl" id="objectionsFrm" class="objFrm">
   <input type="hidden" name="ins_sno" id="ins_sno" value="<?php echo($ins_sno); ?>">
   <strong>Title:</strong> <strong class="text-danger">
    <table class="table table-responsive obj_tbl">
    <tbody>
        <?php $counter = 0; foreach($db->getRecordSet($sql) as $obj){ $counter +=1;?>
        <?php if(isset($obj["do_blanks"]) && !empty($obj["do_blanks"])){ $input_hide_show = 1; }else{$input_hide_show = 0;}?>
            <tr>
                <td><input type="checkbox" onchange="inputBoxShow('<?php echo($input_hide_show);?>','<?php echo(intval($obj['sno']));?>');" name="chk<?php echo($obj["sno"]);?>" id="chk<?php echo($obj["sno"]);?>" value="<?php echo($obj['sno']); ?>"></td>
                <td> <label for="chk<?php echo($obj["sno"]);?>"><?php echo($obj['lbl_title']); ?></label>
                 <?php if(null != intval($obj["do_blanks"]) && intval($obj["do_blanks"]) == 1){?>
                        <input type="text" required placeholder="Type objection details here..." id="blanks_<?php echo($obj["sno"]);?>" name="blanks_<?php echo($obj["sno"]);?>" class="form-control obj-input">
                 <?php } ?>
                 </td>
            </tr>
            <?php }//foreach()  ?>
        </tbody>
    </table>
       <div><i onclick="add_new_obj();" class="fa fa-plus-circle text-success" style="font-size:16px;cursor:pointer;padding-left:3px;"></i></div>
       <div>Return Date</div>
       <div>
            <input type="text" name="return_date" readonly id="return_date" value="<?php echo(date('Y-m-d',strtotime("+10 days"))); ?>" class="form-control">
       </div>
       <div><input type="submit" name="btnSave" id="btnSave" value="Return With Objection(s)" class="btn btn-danger"></div>
       <span id="rst"></span>          
</form>

I have the following jQuery code at the bottom of this page to add the submit event with the above form:

<script type="text/javascript">
    $(document).ready(function(){
        $("form#objectionsFrm").on("submit",function(ev){
            ev.preventDefault();
                $.ajax({
                    url: 'ajaxPhp/saveObjectionsToCase.php',
                    data: new FormData($('form#objectionsFrm')[0]),
                    type:"POST",
                    cache: false,
                    dataType: 'json',
                    success: function(t){
                            if(t['flag'] == 1){
                                    alert('done');
                                   }
                            else{
                                alert('not done');                                                               
                                }
                            },
                    error: function(xhr){
                        $("#rst").html('Error: - '+xhr.status+'</strong>');
                        }
                    });
        })
    })
   </script>

The form is even does not allow to bind the submit event.


Solution

  • I am not an expert on JS but I believe the on ready event works only whenever the markup is loaded, any of your Javascript code shouldn't be executed. The on load event could probably work for some cases.

    A better approach though is to use the event delegation as someone in the comments suggested. The way you use it is this, you pick a common ancestor that your elements are nested(body works every time pretty much) and after the event type(ex. submit) the selector of your element follows.

        $("body").on("submit", "form#objectionsFrm",function(ev){
            ev.preventDefault();
                $.ajax({
                    url: 'ajaxPhp/saveObjectionsToCase.php',
                    data: new FormData($('form#objectionsFrm')[0]),
                    type:"POST",
                    cache: false,
                    dataType: 'json',
                    success: function(t){
                            if(t['flag'] == 1){
                                    alert('done');
                                   }
                            else{
                                alert('not done');                                                               
                                }
                            },
                    error: function(xhr){
                        $("#rst").html('Error: - '+xhr.status+'</strong>');
                        }
                    });
        })