如何使jquery脚本适用于新生成的表单

时间:2015-04-11 20:02:18

标签: php jquery ajax

我有一个脚本显示点击响应中的表单

$(".table th .glyphicon-edit").one('click', function(){
        var $this = $(this);
        var sectionName = $(this).attr('data-sectioname');
        var courseId = $(this).attr('data-courseid');
        var sectionId = $(this).attr('data-sectionid');
    $.get('/edit_section', { section: sectionName, id: courseId, sectionid: sectionId}, function(response) {
        $this.closest('thead tr').after(response);
    });
 });

“edit_section”页面

<form method="POST" action="http://localhost:8000/managecourse/162" accept-charset="UTF-8" id="edit" class="form-horizontal">
  <input name="_method" value="PUT" type="hidden">
  <input name="_token" value="duTA8TbvmYeJWUA21VTGqZYisQZu1ouuhvbXCouv" type="hidden">
  <input name="sectionid" value="1" type="hidden">
  <input name="courseid" value="162" type="hidden">
  <div class="form-group">
   <label for="section_name" class="col-md-4 control-label text-right">Name sectiton</label>
   <div class="col-md-6">
     <input class="form-control" name="section_name" value="Name_section" id="section_name" type="text">
   </div>
  </div>
  <div class="form-group text-center">
   <input name="edit" class="btn btn-primary" value="Save" type="submit">
  </div>
</form>

然后我有脚本提交此表单,但它不起作用

$('#edit').submit(function(e) {
 e.preventDefault();
    var sectionName = $('input#section_name').val();
    var sectionId = $('input[name=sectionid]').val();
    $.ajax({
        type: 'POST',
        cache: false,
        dataType: 'JSON',
        url: '/managecourse/update',
        data: $('#edit').serialize(),
        success:function(data){
            console.log(data);
        },
    });
});

它只显示带有json数据的新页面,但是想要在同一页面上显示这些数据而不重新加载。

1 个答案:

答案 0 :(得分:0)

委派您的提交方法。它将适用于动态添加的元素。

$(document).on('submit','#edit',function(){
   // code
});