In my code for an mini online book store i have a following line repeating 5 times with different value for 'name' parameter
<input name="JSP-2" type="submit" value="Buy">
On clicking the button Buy, the application redirects to a file buy.jsp where it gets the value of name and displays corresponding details of the book.
In my buy.jsp, I have included
<% String bname= request.getParameter("name");
out.print(bname);
%>
But the name doesnt get assigned to bname and it shows the value as null. How do I pass a parameter from the submit type input? Please help.
Like other inputs, the button can have a name and value attribute which will be submitted to your backend on submit. Only the button that was clicked will send its value. You need to use whatever mechanism you're using to access the POSTed variable named action (in this example).
In a button_to, you simply have to add an attribute called “params:” with the params passed as a hash. The params will then be accessible in your controller.
In both the cases, pressing the button will submit the parent form without the need for handling the onclick event separately. If you want to validate the form before submitting, the best event handler would be the onsubmit event of the form.
Value. An <input type="submit"> element's value attribute contains a string which is displayed as the button's label. Buttons do not have a true value otherwise.
You have to pass the parameter in the request. Since you are having a form, and submitting the form, you can have a hidden field in the form called, say "submitType", and populate it whenever you click the button, using javascript. Then this will be available in the next request.
Somewhere inside the form :<input type="hidden" name="submitType">
in the submit buttons:<input name="JSP-2" type="submit" onclick="setType('Buy')">
Javascript: formName is the name of your form
<script>
function setType(type)
{
//formName is the name of your form, submitType is the name of the submit button.
document.forms["formName"].elements["submitType"].value = type;
//Alternately, you can access the button by its Id
document.getElementById("submitId").value = type;
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With