2015-12-14 127 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'>