2015-12-14 129 views
2

我有多个文本框,如何从中获取值。从多个文本框中获取值

$(function() { 
 
    $("#btnAdd").bind("click", function() { 
 
     var div = $("<div />"); 
 
     div.html(GetDynamicTextBox("")); 
 
     $("#TextBoxContainer").append(div); 
 
    }); 
 
    $("#btnGet").bind("click", function() { 
 
     var values = ""; 
 
     $("input[name=a]").each(function() { 
 
      values += $(this).val() + "\n"; 
 
     }); 
 
     alert(values); 
 
    }); 
 
    $("body").on("click", ".remove", function() { 
 
     $(this).closest("div").remove(); 
 
    }); 
 
}); 
 
function GetDynamicTextBox(value) { 
 
    return '<input name = "a" type="text" value = "' + value + '" />&nbsp;' + 
 
      '<input type="button" value="Remove" class="remove" />' 
 
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
 
<form method='POST' action='AddReqPo'> 
 
<input id="btnAdd" type="button" value="Add" /> 
 
<br /> 
 
<br /> 
 
<div id="TextBoxContainer"> 
 
    <!--Textboxes will be added here --> 
 
</div> 
 
<br /> 
 
<input id="btnGet" type="button" value="Get Values" /> 
 
<input type='submit'> 
 
</form>

我要保存值的servlet。但是当按钮提交发送值时,有错误java.lang.NullPointerException。这是servlet文件。当您提交表单(因为你不会阻止默认与preventDefault()提交操作)

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 

    String[] a=request.getParameterValues("a"); 
     System.out.println(a[0]); 
    response.sendRedirect("index.jsp"); 
} 
+0

@RayonDabre这对PHP – Ramanlfc

+0

@Ramanlfc,Yeah..you得到它right..http://stackoverflow.com/questions/11786486/sending-html-form- data-array-to-jsp-servlet可能会有所帮助! – Rayon

+0

这是问题没有验证答案 –

回答

0

关你click处理程序将工作,所以当你的表单提交,声明在servlet String[] a=request.getParameterValues("a");将设置anullSystem.out.println(a[0]); This throwows NullPointerException

+0

你能帮我解决这个问题吗? –

+0

@demahardika在你的处理程序中使用'preventDefault()',并将你的div从表格中移除 – Ramanlfc

+0

请给我示例代码 –

0

该代码工作正常。 Servlet不可访问。 请尝试更改。

<form method='POST' action='AddReqPo'> 

<form method='POST' action='<%=request.getContextPath()%>/AddReqPo'>