如何在表单中获取输入的所有值

时间:2017-05-14 09:58:07

标签: javascript jquery forms

这是我的表单,我尝试在点击提交按钮时从表单中获取所有值

  <form class="well form-horizontal" action=" " method="post"  id="contact_form">
<fieldset>

<!-- Form Name -->
<legend>User Form</legend>

<!-- Text input-->

<div class="form-group">
  <label class="col-md-4 control-label">User Name</label>  
  <div class="col-md-4 inputGroupContainer">
  <div class="input-group">
  <span class="input-group-addon"><i class="glyphicon glyphicon-cloud"></i></span>
  <input  name="name" placeholder="Enter User Name" class="form-control"  type="text">
    </div>
  </div>
</div>
<div class="form-group">
  <label class="col-md-4 control-label">Age</label>  
  <div class="col-md-4 inputGroupContainer">
  <div class="input-group">
  <span class="input-group-addon"><i class="glyphicon glyphicon-cloud"></i></span>
  <input  name="age" placeholder="Enter Age " class="form-control"  type="text">
    </div>
  </div>
</div><div class="form-group">
  <label class="col-md-4 control-label"></label>
  <div class="col-md-4">
    <button name="submitbutton" type="submit" class="btn btn-success" >Submit <span class="glyphicon glyphicon-send"></span></button>
  </div>
</div>

</fieldset>
</form>

然后我编写脚本以在提交时获取所有值

<script type="text/javascript">

$(document).ready(function(){
    $("#submit").click(function(){
        var name = $("#name").val();  
        var age= $("#age").val();  

        console.log(name);
        console.log(age);

    });
});
</script>

但它在提交时记录了这些值。感谢任何帮助

2 个答案:

答案 0 :(得分:1)

您可以使用$('#formId').serialize()函数获取所有表单输入值。但根据你的代码:

<button name="submitbutton" type="submit" class="btn btn-success" >Submit <span class="glyphicon glyphicon-send"></span></button>

您正在使用提交类型button,提交表单并且您的ajax代码中没有任何值。所以改变它:

<button name="submitbutton" type="button" class="btn btn-success" >Submit <span class="glyphicon glyphicon-send"></span></button>

然后再试一次。要获得个人价值,您可以使用

var name = $("#name").val();

带有上述变化。

答案 1 :(得分:1)

$("#submit").click(function(){

您为一个标识为submit的元素指定了一个Click事件处理程序。你的代码中没有这样的元素。

您可以做的是为表单submit event分配处理程序。此外,没有标识为nameage的元素。您可以将查询选择器与输入的名称属性一起使用。

$('#contact_form').submit(function(e) {
  var name = $('#contact_form input[name="name"]').val();
  var age = $('#contact_form input[name="age"]').val();

  console.log(name);
  console.log(age);
});
相关问题