2

I have multiple textboxes, How to get value from it.

$(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>

I want to save values to servlet. But when the button submit send values, there are errors java.lang.NullPointerException. This is the servlet file.

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");
}
Rayon
  • 36,219
  • 4
  • 49
  • 76

2 Answers2

0

none of your click handlers will work when you submit the form(as you aren't preventing the default submit action with preventDefault()), so when your form submits , the statement in the servlet String[] a=request.getParameterValues("a"); will set a to null and System.out.println(a[0]); this throws NullPointerException

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

the code is working correctly. Servlet is not accessible. Try change please.

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

to

<form method='POST' action='<%=request.getContextPath()%>/AddReqPo'>
Gurkan Yesilyurt
  • 2,635
  • 2
  • 20
  • 21