I want to pass a value calculated on the client-side, back to the server. Here is my code:
<script>
var today = new Date();
function startTime() {
document.getElementById('time').innerHTML = today.getTime();
t = setTimeout(function () {
startTime()
}, 1);
}
startTime();
</script>
<form method="POST" action="../frontier/warehouseops/servlet/TimeCalculator">
<input type="hidden" name="time" value="time"/>
<input type="submit" value="Submit" name="buttonSubmit"/>
</form>
What I want to happen is that the value of the javascript variable "time" gets passed to the server. But what is happening, is simply the string "time" is being passed to the server. How do I access the value of a javascript variable and pass it back to the server in a form?
instead of:
document.getElementById('time').innerHTML = today.getTime();
try this:
document.getElementsByName("time")[0].value = today.getTime();
Well
<input type="hidden" name="time" value="time"/>
This line will pass string "time" only as the value attribute of this hiddle form field has "time" as string. What you realy need to do is write a javascript function onSubmit of form and then set the value of this parameter to whatever you want.
<script>
function submit(form)
{
form.time.value = new Date();
document.getElementById("myForm").submit();
}
</script>
<form id="myForm" method="POST" action="../frontier/warehouseops/servlet/TimeCalculator">
<input type="hidden" name="time" value="time"/>
<input type="submit" value="Submit" name="buttonSubmit" onClick="submit(this.form)"/>
</form>
Hope this helps
Related
I'm writing code for currency exchanger in spring boot (I'm a begginer) and right now I'm stuck on thymeleaf template. Right now my template looks like this :
<div align="center">
<form th:action = "#{/postCurrency}" method = "POST">
<label for="firstNumber"></label>
<input id = "firstNumber" type="number" name = "fNumber"/>
<br/>
<br/>
<input type="submit" value="Submit">
</form>
</div>
So this means that I have one "box" where user types in number and now I want to have a second "box" where currency will be exchanged and automatically shown in that "box", How do I do that ?
EDIT : My template now looks like this (exchange.html):
<form th:action = "#{/postCurrency}" method = "POST">
<label for="firstNumber"></label>
<input id = "firstNumber" type="number" name = "fNumber"/>
<br/>
<br/>
<input type="submit" value="Submit">
<br/>
<br/>
<input type = "number" th:field="*{resultNumber}" disabled/>
</form>
My controller class :
#PostMapping("/postCurrency")
public String postExchange(#RequestParam Double fNumber , Model model){
Double number = exchangeLogic.exchange(fNumber);
model.addAttribute("resultNumber",number);
return "redirect:/exchange";
}
The problem is that thymleaf can't read the modelattribute , I need to take "resultNumber" and make it visible in form tag
In your controller try this.
#PostMapping("/postCurrency")
public String postExchange(#RequestParam Double fNumber , Model model){
Double number = exchangeLogic.exchange(fNumber);
model.addAttribute("resultNumber",number);
return "exchange";//your html page
}
and in your html page
<input type = "number" th:value="${resultNumber}" disabled/>
let me know if it works for you.
I hooked login.jsp and wrote following code in it:-
<script>
function a(){
var otp=document.getElementById("otpText").value;
document.location.href="?otp="+otp;
<% System.out.println(request.getParameter("otp")); %> //printing null
return false;
}
</script>
<form name="otp" method="post" action="" >
Enter otp:
<input type="text" name="otpText" id="otpText"/>
<input type="submit" value="Submit" onClick="return a()"/>
</form>
I typed some value inside otpText and that value is displayed in the url when I submitted the form. But when I am printing that value as in above code,it is printing null. I need that value as I want to store the same into session.Please help, any help would be appreciated.
If you change your code to
var otp=document.getElementById("otpText").value;
console.log (otp); // or alert (otp);
document.location.href="?otp="+otp;
you will see the value.
im currently creating a canvas Javascript game and im passing localstorage variable to my database which is the Score. Score being 'elapsed'. When i was debugging i saw that the localstorage value is there. But it just doesnt seem to store into the database. Preferably without the use of Ajax?
function drawElapsedTime(){
var elapsed=parseInt((new Date() - startTime)/1000);
g.save();
g.beginPath();
g.fillStyle="#008000";
g.font="14px Verdana"
// draw the running time at half opacity
g.globalAlpha=0.50;
g.fillText(elapsed+" secs",canvas.width-75,25);
localStorage.setItem("score",elapsed);
g.restore();
}
var storedTime = localStorage.getItem("score");
<form action="UserActionServlet" method="post">
<input type="submit" value="scoreObj" class="submit" />
</form>
Command:
String xscore = request.getParameter("score");
int score = 0;
if (xscore != null) {
score = Integer.parseInt(xscore);
}
System.out.println(xscore);
You are not passing the score variable as a parameter in your form post.
<form action="UserActionServlet" method="post" onSubmit="submitForm(this.form)">
<input type = "hidden" name = "score"/>
<input type="submit" value="scoreObj" class="submit" />
</form>
<script>
function submitForm(f){
f.score.value = storedTime ;
f.submit();
}
</script>
I am currently developing a web site (Part of a university assignment)
I just put some input validation, although when I redirect due to an error from validation,
For example:
var x = document.getElementById("age").checked;
var y = document.getElementById("agreement").checked;
var z = document.getElementById("sex").value;
if(x != true & y != true & z == null)
{
response.sendRedirect("Register.jsp");
}
I was looking to have some sort of error message appear above the form, to tell the user that they have created an error within the form. (For example, if they did not enter their Gender or did not agree to either of the checkboxes). Also noted, I will change the validation code slightly to be more specific to the error in which the person has made.
Form:
<h3>Register as user</h3>
<form method="POST" action="Register">
<ul>
<li>First Name: <input type="text" name ="firstName"></li>
<li>Last Name: <input type = "text" name = "lastName"></li>
<li>Email Address: <input type = "email" name = "email"></li>
<li>Gender: Male <input type ="radio" name ="sex" value="male">
Female <input type ="radio" name ="sex" value="female"></li>
<li>User Name <input type="text" name="username"></li>
<li>Password <input type="password" name="password"></li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12: <input type = "checkbox" name="age"></li>
<li>Please check this box to agree to the Terms and Conditions <input type ="checkbox" name="agreement"></li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
Thank you for any help or advice you can give me, I really appreciate it as I am rather new to web development and I want to improve and understand techniques that web developers use.
var validate = function(form) {
var errors = [];
if (!form.sex[0].checked && !form.sex[1].checked) {
errors.push('Please select a gender');
}
if (!form.agreement.checked) {
errors.push('Please agree to T&C');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
};
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" onsubmit="return validate(this);">
<ul>
<li>First Name:
<input type="text" name="firstName">
</li>
<li>Last Name:
<input type="text" name="lastName">
</li>
<li>Email Address:
<input type="email" name="email">
</li>
<li>Gender: Male
<input type="radio" name="sex" value="male">Female
<input type="radio" name="sex" value="female">
</li>
<li>User Name
<input type="text" name="username">
</li>
<li>Password
<input type="password" name="password">
</li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12:
<input type="checkbox" name="age">
</li>
<li>Please check this box to agree to the Terms and Conditions
<input type="checkbox" name="agreement">
</li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
I did something like this. I have an html element which is hidden by default.
It is red and take the whole width of the div I put into.
And I've a function to manage errors :
var manageError = function(message) {
$("#element").val(message); // or $("#element").html(message) I guess
$("#element").clearQueue();
$("#element")slideDown(200).delay(10000).slideUp(200);
};
Does it help ?
use jQuery to do this. since you are learning..it will be more helpful for you.
first thing I noticed there, you have used response.sendRedirect(...); in side your javascript which is a wrong approach.
And in your form, don't use un-ordered list like approach, simply use div tags.
I will give a simple example:
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" id="formId">
First Name:
<input type="text" name="firstName">Last Name:
<input type="text" name="lastName">
<div id="errMsg"></div>
<input type="button" value="submit" id="submtBtn">
</form>
and in your javascript file, use it with jQuery:
< !DOCTYPE html >
< html >
< head >
< script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > < /script>
</head >
< script >
$("submtBtn").click(function({
var errorMsg = "";
if ($("firstName").val === '' || $("lastName").val === '') {
errorMsg = "<b>firstName and LastName can not be empty!<b>";
$("errMsg").html(errMsg);
return;
}
$("#formId").submit();
});
< /script>
you can follow above approach.... if you're using Servlets, you could follow jQuery Ajax to submit your values. try and see...hope it will give you an idea..!
First put the validation code in a function and call that function.
function validate(){
..........write your validation code
}
Call this from submit button via onclick or onchange or onblur attribute of input tag.
You can always use HTML 5. With the required action. They can never leave anything blank if this is in. Be aware that it might work with a space in it or something.
Try this:
<li>First Name: <input type="text" name ="firstName" required></li>
I have created dynamic row on click of button in table using following code :
<script type="text/javascript">
var counter = 1;
function displayResult()
{
counter++;
document.getElementById("myTable").insertRow(-1).innerHTML = '<td><select name="list_dispatch_state" id="list_dispatch_state"><option value="01">01</option><option value="02">02</option><option value="03">03</option></select></td><td><input type="text" name="txt_email'+ counter +'" id="txt_email'+ counter +'" value='+ counter +'></td>';
}
</script>
<body>
<form action="Dogetdat" method="post">
<table id="myTable" border="1">
<tr>
<th>Select</th>
<th>Value</th>
</tr>
</table>
<br />
<button type="button" onclick="displayResult()">Insert new row</button>
<input type="submit">
</form>
</body>
my question is that, on click of button new row and control inside it created but when I click on submit then form submitted to servlet page.
Then how servlet will know that how many data are received ?
Because in servlet I ll get data using
String str1= request.gerParameter("txt_email");
how servlet will know that how many variable it have to create and what will be the name of that ? what will I have to pass in request.gerParameter(""); ?
You have to use the following request.getParameterValues and get the result as an array
String emails[] = request.getParameterValues("txt_email");