I have a jsp page with this code:
<script type="text/javascript">
function getWithdrawAmmount()
{
var withdraw=document.forms["WithdrawDeposit"]["AmountToWithdraw"].value;
document.getElementById('hidden').type = withdraw;
}
</script>
<form method="POST" name="WithdrawDeposit" onsubmit="getWithdrawAmmount()">
<table>
<tr><td><input type="text" size=5 name="AmountToWithdraw"></td>
<td><input type="button" value="Withdraw"></td></tr>
</table>
</form>
<input type="hidden" name="hidden" value="">
<% String AmountWithdraw = request.getParameter("hidden"); %>
<%!
public void Withdraw(){
int Amount = Integer.parseInt("AmountWithdraw");
Deposit deposit = new Deposit();
deposit.WithdrawMoney(AmountWithdraw);
} %>
I need to activate the Withdraw() method on form submit and get the text input.
the javascript hold the value inserted in 'hidden' and i can access it later.
but i can't call to : <% Withdraw(); %> from inside javascript.
how can i call Withdraw() after button click?
10x
First off your line of code has issues
document.getElementById('hidden').type = withdraw;
It is looking for an element with an id of hidden. Not a name, an id. So add an id to the element you are referencing.
Second you are setting a type. Don't you want to set the value?
So the HTML would look like
<input type="hidden" name="hidden" id="hidden" value="" />
and the JavaScript would be
document.getElementById('hidden').value = withdraw;
Now if you want to call a function on the server, you either need to post back the form or make an Ajax call.
Related
Improper Form Submission
For the below code snippet, I am not able to get any value for the input hidden field in my request.
In the form table created:
It is working fine, if I click the Approve button of the first row.
Issue is faced when Approve button of intermediate row is clicked.
There is no any value passed in the request for the id="hidinput";
<script>
function fetchID(){
var contentID = document.getElementById("testID").innerHTML;
document.getElementById("hidinput").value=contentID;
}
</script>
<%for (APPL_Testimonial_Txn testimonial_Txn : results) {%>
<tr>
<form action="<%=approve.toString()%>" method="POST">
<td id="testID"><%=testimonial_Txn != null ? testimonial_Txn
.getTestimonialId() : ""%></td>
<input type="hidden" name="rowId" id="hidinput" value=""/>
<td><button class="button-continue ContinueNew" type="submit"
onclick="fetchID()">APPROVE</button></td>
</form>
</tr>
<%}%>
Please find below screen capture of the table.
As per the code above, there is no way to figure out the row in which approve button was clicked. You can pass the testimonial Id to a fetchID function.
<script>
function fetchID(contentID){
document.getElementById("hidinput").value=contentID;
}
<script>
<tr>
<form action="<%=approve.toString()%>" method="POST">
<td><%=testimonial_Txn != null ? testimonial_Txn
.getTestimonialId() : ""%></td>
<input type="hidden" name="rowId" id="hidinput" value=""/>
<td><button class="button-continue ContinueNew" type="submit"
onclick="fetchID('<%=testimonial_Txn != null ? testimonial_Txn
.getTestimonialId() : ""%>')">APPROVE</button></td>
</form>
</tr>
<%}%>
Thanks for the suggestion.
I changed the position of form tags, means kept form tag outside the loop construct keeping form as unique and it worked. :)
(I know the questions is a bit long but I do believe solution is easy, so would really appreciate it if someone can help me have a look)
I am trying to write a school system, where you can enter a student's name, year, grade, on a webpage, and save the student's info to produce a list. I would like it to have two "buttons" on the webpage:
One is "save and next", i.e. if you finished entering one student info, click this, the info get saved and the webpage renew to enter the next student info.
Second is "save and finish", i.e. if this is the final student you want to enter, click this and the last student info get saved, and webpage is redirected to the next page where it shows a list of all student info.
To achieve this, in JSP, I used two HTML forms, and one of them I used javascript to try to submit to servlet, But I must have done something wrong because it does not work properly:
Here are my codes:
InputGrade.jsp:
<html>
<head>
<title>Title</title>
</head>
<body>
The first form: used input labels for users to enter info, also used input label to create a submit button "save it next":
<form action = "InputGradeServlet" method="POST">
<table>
<tr>
<td>
Enter Student Name: <input type="text" id="stName" name = "stName" />
</td>
<td>
Enter Subject: <input type="text" id="Subject" name = "Subject" />
</td>
<td>
Enter Grade: <input type = "text" id="Grade" name = "Grade" />
</td>
<td>
<input type="submit" value="save and next"/>
</td>
</tr>
</table>
<input type="text" name = "flag" style="display: none" value="1"/>
</form>
The second form include the "save and finish" button, but use javascript to submit the information: (I think where the problem is)
User still enter student info in the first form, but the javascript function use getElementById function to acquire the info in first form
<form name="form2" action ="InputGradeServlet" method="POST" >
<input type="text" name = "flag" style="display: none" value="2"/>
<button onclick="finSaveFunc()">Finish and submit</button>
<script>
function finSaveFunc() {
var stName = document.getElementById("stName")
var Subject = document.getElementById("Subject")
var Grade = document.getElementById("Grade")
document.stName.submit();
document.Subject.submit();
document.Grade.submit();
}
</script>
And in the Servlet, a list created to add the students the user entered
public class InputGradeServlet extends HttpServlet {
List<Student> inputStList = new <Student>ArrayList();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if user press "save and next" button, form one is submitted, and servlet do the action of saving student to the list and redirect to the same JSP file i.e. redirect the the same webpage again of entering the next student:(also might be problematic)
if (request.getParameter("flag").equals("1")) {
request.getParameter("Grade");
...... (get other info: name, year ect)
inputStList.add(findstudent); //add student entered to the list
response.sendRedirect("InputGrade.jsp");
}
}
}
If user press "save and finish", i.e. submitting the second form, and servlet again add the final student entered to the list and redirect to the next webpage showing the whole list:
}else if (request.getParameter("flag").equals("2")) {
request.getParameter("Grade");
....
inputStList.add(findstudent);
request.getSession().setAttribute("inputStList",inputStList);
response.sendRedirect("ShowList.jsp"); }
This is where it gets problematic: when submitting the first form hitting "save and next" button it works fine, but when submitting the second from hitting "save and finish" button, it returns error.
Therefore I would really appreciate it if some can help me have a look?
There are many reason that's why you can get a NullpointerException.
Rule of Thumbs : If you want to compare a string then first check if it is not null.
According to your requirement I am giving a solution that how can you do that.
Suppose your form be like:
<html>
<head>
<script>
function _submit(flagVal) {
document.getElementById('flagValId').value=flagVal;
document.getElementById('someFormId').submit();
}
</script>
</head>
<body>
<form action = "InputGradeServlet" method="POST" id="someFormId">
<table>
<tr>
<td>
Enter Student Name: <input type="text" id="stName" name ="stName" />
</td>
<td>
Enter Subject: <input type="text" id="Subject" name = "Subject" />
</td>
<td>
Enter Grade: <input type = "text" id="Grade" name = "Grade" />
</td>
<td>
<input type="button" value="save and next" onclick="_submit('1')"/>
<input type="button" value="save and exit" onclick="_submit('2')"/>
</td>
</tr>
</table>
<input type="hidden" id="flagValId" name = "flag" value=""/>
</form>
</body>
</html>
Now when you click save and next button, then it set flagVal 1 and if we click save and exit button then it sets flagVal 2. After setting the flagVal it submits the form. After submitting your from you should check first that what is your flagVal. So in doPost method
if (request.getParameter("flag")!=null && request.getParameter("flag").equals("1")) {
//Add your student in this block and show the input page again.
response.sendRedirect("InputGrade.jsp");
}else if (request.getParameter("flag")!=null && request.getParameter("flag").equals("2")) {
//Add your student in this block and show the list.
response.sendRedirect("ShowList.jsp");
}
Hope that helps.
You don't get form1 values. You post form2 values so you get null error.
Try it please:
function finSaveFunc() {
var stName = document.getElementById("stName")
var Subject = document.getElementById("Subject")
var Grade = document.getElementById("Grade")
var newForm = document
.getElementById("form2")
.appendChild(stName)
.appendChild(Subject)
.appendChild(Grade);
newForm.submit();
}
I have a form with input field and this input contain a drop down menu read information from database.
If the user enters value and when he arrives to the drop menu he doesn't find what he wants he go to another page to add this info to the drop down menu and then go to the first page to continue enter the information.
How can I keep this information if he goes to another page to add info to drop menu and how can after adding the info to drop menu find this info without refresh and without submit.
This is the first page with the form
<form name='' method='post' action='<?php $_PHP_SELF ?>'>
<input name='txt_name' id='' type='text'>
This drop menu read from database
<select id="groups" name="txt_label" class="form-control">
';?>
<?php
$sql=mysqli_query($conn,"select DISTINCT db_label from tbl_label")or die(mysqli_error($conn));
echo'<option value="">-- Select --</option>';
while($row=mysqli_fetch_array($sql)){
$label=$row['db_label'];
echo "<option value='$label'>$label</option>";
}echo'</select>';?><?php echo'
</div>
</form>
Second form in another page
<form class="form-inline" role="form" name="form" method="post" action="';?><?php $_PHP_SELF ?><?php echo'">
<div class="form-group">
<label for="pwd">Label</label>
<input id="txt_label" name="txt_label" type="text" placeholder="Label" class="form-control input-md">
</div>
<div class="form-group">
<label for="pwd">Sub Label</label>
<input id="txt_sublabel" name="txt_sublabel" type="text" placeholder="SubLabel" class="form-control input-md">
</div>
<input type="submit" name="addlabel" value="Add" class="btn btn-default">';
EDIT: Keep value of more inputs
HTML:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
<input type="text" id="txt_2" onkeyup='saveValue(this);'/>
Javascript:
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
if the above code did not work try this:
<input type="text" id="txt_1" onchange='saveValue(this);'/>
<input type="text" id="txt_2" onchange='saveValue(this);'/>
You can also use useContext() from react context() if you're using hooks.
In MVC/Razor,
first you should add a variable in your model class for
the textBox like this:
namespace MVCStepByStep.Models
{
public class CustomerClass
{
public string CustomerName { get; set; }
}
}
Then in Views --> Index.cshtml file make sure the Textbox
is created like this:
#Html.TextBoxFor(m => m.CustomerName)
For a complete example, please check out this site:
How to update a C# MVC TextBox By Clicking a Button using JQuery – C# MVC Step By STep[^]
So I have a page called Index.cshtml
I have this input in a form with the id "cvr":
#using (Html.BeginForm("SendMailAsACompany", "Contract", null, FormMethod.Post, new { id = "cvr" }))
{
<input type="hidden" value=#Html.ViewData.Model.StudentId name="studentId" />
<input type="hidden" value=#Html.ViewData.Model.CompanyId name="companyId" />
<input type="hidden" value=#Html.ViewData.Model.ApplicationId name="applicationId"/>
if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
<input type="text" name="companyCVR" placeholder="Indsæt CVR-nr."/>
}
}
and at the bottom of the page I have the submit button with the id above ("cvr") where I am trying to add two more forms to pass on to the controller (repFirstName and repLastName):
#if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
using (Html.BeginForm("SendMailAsACompany", "Contract", null, FormMethod.Post, new { id = "cvr" }))
{
<input type="text" name="repFirstName" placeholder="Indsæt fornavn" />
<input type="text" name="repLastName" placeholder="Indsæt lastnavn" />
}
<input type="button" value="Submit" onclick="$('#cvr').submit();" class="btn btn-success" />
}
However they will not pass on submit, only the first value (the CPR above). However if I have all three values at the start, they will pass successfully.
How can I have the input in both places and still be able to submit and pass the data to the controller? Do I need two separate forms/ids ?
Only one form is required, remove the second form declaration and associate element with form using form attribute which is defined at the bottom of page.
The form attribute is used to associate an input, select, or textarea element with a form (known as its form owner).
#if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
<input type="text" name="repFirstName" placeholder="Indsæt fornavn" form="cvr"/>
<input type="text" name="repLastName" placeholder="Indsæt lastnavn" form="cvr"/>
<button form="cvr" class="btn btn-success">Submit</button>
}
If your generated HTML results in multiple elements that have the same ID, and then you have some inline javascript like this:
<input type="button" value="Submit" onclick="$('#cvr').submit();" />
Then the above javascript will work only for the first #cvr
That is one example of why you cannot / must not have multiple elements on the page with the same ID.
You must refactor your code to only use one element with any given ID. If need to have multiple elements with same moniker, use a class - so your javascript would become:
<input type="button" value="Submit" onclick="$('.cvr').submit();" />
and your generated HTML would be class="cvr" instead of id="cvr"
Alternately, you could ensure that each of your forms uses a different ID, such as id="cvr1", id="cvr2", id="cvr3" and then your javascript could be:
<input type="button" value="Submit" onclick="$('#cvr1, #cvr2, #cvr3').submit();" />
I have several forms in HTML, each with a submit button and a hidden field. The same javascript function is called when any of the submit buttons are pushed. I want to know which submit button has been pushed. I think I can do this by finding out what the hidden field value is of the corresponding form - but I'm having difficulty with this. My HTML is:
<div id="existingPhotosList">
<table><tbody><tr><td>
<img src="./userPictures/IMG0001.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0001.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
<tr>
<td>
<img src="./userPictures/IMG0002.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0002.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
</tbody>
</table>
</div>
There may be more or less table rows with images and forms on them - depending on how many images are found on the server.
The javascript I have right now is:
$('.deleteFiles').submit(deleteFile);
function deleteFile() {
var myValue = $(this).parent().closest(".picture").val();
alert(myValue);
return false;
}
I'm currently getting undefined as the result of the alert.
I want to know which submit button has been pushed.
As each of your forms only has one submit, you don't have to change your code much.
this in your submit handler will refer to the form, and the element is within the form, so:
var myValue = $(this).find("input[name=picture]").val();
No need to go up to the parent, and closest goes up the ancestry (through ancestors), not down. find goes down (descendants).
the simplest way I think will be:
var myValue = $('input[name=picture]', this).val();
should be:
var myValue = $(this).closest(".deleteFiles").find("input[type=hidden]").val();
here is the demo http://jsfiddle.net/symonsarwar/963aV/
$('.deleteFiles').click(deleteFile);
function deleteFile() {
var me=$(this).closest('tr').find('td:eq(1) input').val();
alert(me)
}