jquery表单.submit事件未触发

时间:2018-03-22 18:00:18

标签: javascript jquery html5 bootstrap-modal

我正在尝试触发表单上的提交事件并验证它。在我的代码中有两件事情不起作用,第一件事是未触发onsubmit事件,第二件事是电子邮件类型的输入字段未经验证我使用了html5输入类型的电子邮件并且需要但仍然没有成功。我不知道我做错了什么。这是代码:

<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Learn PHP CodeIgniter Framework with AJAX and Bootstrap</title>
    <link href="<?php echo base_url('assests/bootstrap/css/bootstrap.min.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assests/datatables/css/dataTables.bootstrap.css')?>" rel="stylesheet">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
    <div class="container">
        <h3>Contacts</h3>
        <br />
        <button class="btn btn-success" onclick="add_contact()"><i class="glyphicon glyphicon-plus"></i> Add Contact</button>
        <br />
        <br />
        <table id="table_id" class="table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th style="width:0px;"></th>
                    <th>first name</th>
                    <th>last name</th>
                    <th>phone</th>
                    <th>email</th> 
                    <th style="width:125px;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($contacts as $contact){?>
                    <tr>
                        <td style="width:0px;"><?php echo $contact->id;?></td>
                        <td><?php echo $contact->first_name;?></td>
                        <td><?php echo $contact->last_name;?></td>
                        <td><?php echo $contact->phone;?></td>
                        <td><?php echo $contact->email;?></td>
                        <td>
                            <button class="btn btn-warning" onclick="edit_contact(<?php echo $contact->id;?>)"><i class="glyphicon glyphicon-pencil"></i></button>
                            <button class="btn btn-danger" onclick="delete_contact(<?php echo $contact->id;?>)"><i class="glyphicon glyphicon-remove"></i></button>
                        </td>
                    </tr>
                 <?php }?>
            </tbody> 
            <tfoot>
                <tr>
                    <th style="width:0px;">ID</th>
                    <th>first name</th>
                    <th>last name</th>
                    <th>phone</th>
                    <th>email</th>
                    <th>Action</th>
                </tr>
            </tfoot>
        </table> 
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script src="<?php echo base_url('assests/bootstrap/js/bootstrap.min.js')?>"></script>
    <script src="<?php echo base_url('assests/datatables/js/jquery.dataTables.min.js')?>"></script>
    <script src="<?php echo base_url('assests/datatables/js/dataTables.bootstrap.js')?>"></script> 
    <script type="text/javascript">
        $(document).ready( function () {
            $('#table_id').DataTable();
            $('#form').submit(function(event) {
                save();
                event.preventDefault();
            });
        } );
        var save_method; //for save method string
        var table;


        function add_contact()
        {
            save_method = 'add';
            $('#form')[0].reset(); // reset form on modals
            $('#modal_form').modal('show'); // show bootstrap modal
            //$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
        }

        function edit_contact(id)
        {
            save_method = 'update';
            $('#form')[0].reset(); // reset form on modals

            //Ajax Load data from ajax
            $.ajax({
                url : "<?php echo site_url('contacts/ajax_edit/')?>/" + id,
                type: "GET",
                dataType: "JSON",
                success: function(data)
                {
                    $('[name="id"]').val(data.id);
                    $('[name="first_name"]').val(data.first_name);
                    $('[name="last_name"]').val(data.last_name);
                    $('[name="phone"]').val(data.phone);
                    $('[name="email"]').val(data.email);


                    $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                    $('.modal-title').text('Edit Contact'); // Set title to Bootstrap modal title

                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    alert('Error get data from ajax');
                }
            });
        }

        function save()
        {
            console.log("submitting");
            var url;
            if(save_method == 'add')
            {
                url = "<?php echo site_url('contacts/contact_add')?>";
            }
            else
            {
              url = "<?php echo site_url('contacts/contact_update')?>";
            }
            if($('#form')[0].checkValidity())
            // ajax adding data to database
                $.ajax({
                    url : url,
                    type: "POST",
                    data: $("#form").serialize(),
                    dataType: "JSON",
                    //contentType: 'application/json; charset=utf-8',
                    success: function(data)
                    {
                        //console.log(url);
                        //if success close modal and reload ajax table
                        $('#modal_form').modal('hide');
                        location.reload();// for reload a page
                    },
                    error: function (jqXHR, textStatus, errorThrown)
                    {
                        alert('Error adding / update data');
                    }
                });
            else
            {
                return false;
            }
        }

        function delete_contact(id)
        {
            if(confirm('Are you sure delete this data?'))
            {
            // ajax delete data from database
                $.ajax({
                    url : "<?php echo site_url('contacts/contact_delete')?>/"+id,
                    type: "POST",
                    dataType: "JSON",
                    success: function(data)
                    {

                       location.reload();
                    },
                    error: function (jqXHR, textStatus, errorThrown)
                    {
                        console.log(errorThrown);
                        alert('Error deleting data');
                    }
                });
            }
        }

    </script>

    <!-- Bootstrap modal -->
    <div class="modal fade" id="modal_form" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h3 class="modal-title">Contact Form</h3>
                </div>
                <div class="modal-body form">
                    <form action="#" id="form" class="form-horizontal" onsubmit="save();">
                        <input type="hidden" value="" name="id"/>
                        <div class="form-body">
                            <div class="form-group">
                                <label class="control-label col-md-3">first name</label>
                                <div class="col-md-9">
                                    <input name="first_name" placeholder="first name" class="form-control" type="text">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-md-3">last name</label>
                                <div class="col-md-9">
                                  <input name="last_name" placeholder="last name" class="form-control" type="text">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-md-3">phone</label>
                                <div class="col-md-9">
                                    <input name="phone" placeholder="phone" class="form-control" type="text"> 
                                </div>
                            </div>
                            <div class="form-group">
                                    <label class="control-label col-md-3">email</label>
                                    <div class="col-md-9">
                                        <input type="email" name="email" placeholder="email" class="form-control requiredField" required>
                                    </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <input type="submit" id="btnSave" class="btn btn-primary" value="save">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    <!-- End Bootstrap modal --> 
</body>

2 个答案:

答案 0 :(得分:1)

您需要提交按钮才能位于表单元素中。现在它被放置在表单之外。

<html>
  <head>
    <meta charset="utf-8">
    <title>TITLE</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    .bgimg {
      min-height: 100%;
      min-width: 1024px;
      width: 100%;
      height: auto;
      position: fixed;
      top: 0;
      left: 0;
      z-index: -1;
      opacity: 0.8;
    }
    .vdeo {margin: 10% 8%; }
    </style>
  </head>
  <body>
    <img class="bgimg" src="https://wallpaperclicker.com/wallpaper/HD-Happy-Birthday-Cartoon-Wallpaper/20306228/">
    <iframe class="vdeo" width="600" height="345" align="middle" src="https://www.youtube.com/embed/XXXXXXXX?autoplay=1&controls=0"></iframe>
      <script>
      for (var i=0;i<4;i++) {
        alert(
          (i===2)?"Happy Birthday, dear Hub Hub!":"Happy Birthday to YOU!"
        )
      }
      </script>
</iframe>
  </body>
</html>

Example。请注意,PHP不起作用,但您会看到表单提交。

答案 1 :(得分:0)

您在模式框中有一个表格要提交。