Javascript function not showing second form name

2019-09-09 13:07发布

I have 2 forms with different ids, in javascript function I'm going to get form id in variable name, but in name variable only first forms id is going, not going form 2 id my code is.

HTML

<form name="form" id="filterMemberByFamNum" class="form-horizontal" role="form">
  <div class="form-group">
    <label>Family Number</label> <input type="text" name="familyNumber" placeholder="Family Number" class="form-control">
  </div>
  <button type="button" class="btn btn-primary" onclick="filterMembers();return false;">Submit</button>
</form>

<form name="form" id="filterMemberByMemName" class="form-horizontal" role="form">
  <div class="form-group">
    <label>Member Name</label> <input type="text" name="member" placeholder="Member Name" class="form-control">
  </div>
  <button type="button" class="btn btn-primary" onclick="filterMembers();return false;">Submit</button>
</form>

JS

function filterMembers() {
  //alert("Submitted");
  var str = $("form").serialize();
  var name = $(this.form).attr('id');

  console.log(name);

  $.post("model/handler.php?name=" + name + "&op=formSubmit", {
    'data': str
  }, function(data) {
    $('#members').html(data);
  }, "json");

  return false;
}

Any time output result in console tab is filterMemberByFamNum infact I'm submitting filterMemberByMemName form.

Please help me.

1条回答
疯言疯语
2楼-- · 2019-09-09 13:43

Your javascript as written doesn't know how to differentiate between the 2 forms because you are calling serialize() on $("form") - you have 2 forms, so it's gonna pick the first it finds. That's just part of the problem. You have 2 forms with the same name attribute. Those should be unique.

Since you are already using jQuery, rewrite this as

$(".form-horizontal").on( "submit", function( event ) {
  var str = $(this).serialize();
  var name = $(this).attr('id');
  console.log(name);
  $.post("model/handler.php?name="+name+"&op=formSubmit",
    {
        'data':str
    },function(data){
        $('#members').html(data);
    },"json");
  return false;
});

and remove the onclicks on the buttons. You'll actually need to also make the button type="submit" as well.

jsfiddle example

查看更多
登录 后发表回答