saving value from form doesn't work - javascript

So, storing a Java String into a form hidden input value. I call said value via javascript and attempt to store it into a var. Strangely, I can display the value via alert but javascript crashes when I try to save it into a var.
The first line is from the initializing jsp file. It does some stuff that gets the string. The string is a list of ints that I plan on splitting in javascript for some stuff.
"<form id = \"listArrForm\"> <input id = \"listArr\" value = "+ output +" type = \"hidden\"></form>"
var listArr = document.getElementById("listArr").value; //Does work
alert(document.getElementById("listArr").value); //Does work
So yea, I'm guessing it has to do with the the type of value being retrieved?

Well, both should work as you can see in this jsfiddle: http://jsfiddle.net/2eWja/
What are you storing in the value that makes the script not work? Are you sure you're not putting quotes in?

what browser are you using? There could be problem for some
Btw using getElementById is known to be wrong. ;)

Related

Getting Request Parameter Value Writes the Result into the Source?

I'm new to JavaScript and JQuery, but I've been able to get around and it's been fun. I came across something at work, however, that is boggling my mind. And it's not something I really know how to explain either, so I attached a screenshot.
I have this function (there are a few variables that I have access to such as $formItem, $request, $object, $jQuery, $widgetId, $ajaxUrl, and params, that are given to me):
<input type="hidden" name="SomeRandomName" id="SomeRandomId" value="Hello"/>
function reload(element) {
var result = $request.getParameter("SomeRandomId");
console.log("Result");
console.log(result);
}
When I load the page, I get this issue.
https://i.imgur.com/aASflls.png
It seems the value is being written directly into the code? If I try to wrap the result in strings or append it, I get an error saying it's not possible. What can I do in this situation?
Let me know if you need anything else. This is the first time I've encountered this problem.
I've tried using jQuery, but the data disappears when the form is submitted and that is an issue at work. We need the data to persist when the form is submitted and bounced back. The process we do that in is by calling $request and assigning a velocity variable the data. I could not do this procedure in this case because I am dynamically re-assigning HTML elements their original value.
When you are assigning result to 'Hello' in console it should be in single quotes as it's a string. Should be let result = 'Hello'.

Setting an element value using HTML entities

I'm having an issue trying to set an input field's value when using HTML entities in that they are coming out literally as " rather than ".
Here is the code I am using:
document.getElementById('inputSurname').setAttribute('value', 'test"""');
in which the output is test""" though I want the output to be test""".
It doesn't look like a double-encoding issue since in the source code I am seeing it the same way I have set it here.
I know I could decode the value from its HTML entity format though this is something I want to avoid if possible for security.
Any help would be much appreciated :)
Try this:
document.getElementById('inputSurname').value = 'test"""';
Or if you want to keep &quot:
function myFunction() {
document.getElementById('myText').value = replaceQuot('test&quot&quot&quot');
}
function replaceQuot(string){
return string.replace('&quot', '""');
}
Or you can use escape characters.
document.getElementById("inputSurname").setAttribute("value", "test\"\"\"\"");
Well you could just write the new value as 'test"""'.
For other characters however, I'm going to refer you to this answer: HTML Entity Decode

jquery val not passing data

I've got several input fields and such jquery code:
jQuery(document).ready(function($){
$('input').change(function(){
var amount1=$('.product-addon-wesprzyj-autora input').val();
var amount2=$('#pa_kategoria-cenowa').val();
var amount3=$('.quantity .qty').val();
var fractal=0.01;
var Total=(amount1*amount2*fractal*amount3)+(' PLN');
$('.product-addon-kwota-dla-autora input').attr('value', Total);
});
});
Strange thing is that jquery code works. In real time in changes values in my inputs, BUT after clicking sumbit, value from '.product-addon-kwota-dla-autora input' seems to be empty in database. Why is that? is there any way of pushinig this code to work? If i will type via keyboard data into that field, everything works. ANy ideas what is here wrong?
With the code you provided, I am not quite sure what your problem is. It could be a problem in your server side code where you save the data to the table. You need to debug and that find out.
But make sure that you are setting the form values properly so that your server side code will have the correct data from the form. You may consider using the val() method to set value.
$('.product-addon-kwota-dla-autora input').val(Total);
Also , when you read values from form inputs and use it for numeric operations, Consider converting the type to a numeric version by using parseFloat() or parseInt()
var Total=parseFloat(amount1)*parseFloat(amount2)*parseFloat(fractal)
*parseFloat(amount3)+(' PLN');
Also, You may inspect your browser's network tab to see what data your browser is posting to the server code. That should help you to understand where your problem is.
it might me that your "Total" variable is empty. alert('Total') and check for result. if it shows some value then try to change your line from this
$('.product-addon-kwota-dla-autora input').attr('value', Total);
into this
$('.product-addon-kwota-dla-autora input').val(Total);

Pass variable from JSP to Javascript

Inside a JSP, I am fetching data from a Servlet by this code
<%
String name=(String)request.getAttribute("filepath");
%>
I want to access this inside script tags, how should i go about it?
I tried this var n = "${name}" and var n = "<%=name%>" and it did not work.
Make sure the assignment in scriptlet is working. Try System.out.println(name); to see if the value is set correctly.
I often use the latter
var n = "<%=name%>";
Both options should work fine (do not forget the ;).
Just remember that the scriptlet/ EL are executed when the page is returned from the server and the JavaScript when the browser parse the HTML.
To debug this issue I would use scriptlet first and look if I have a value using browser "view source".
If you do not see any value i.e.
var n = "";
You did not set the attribute correctly in java.
As for EL usage. Make sure you have the correct setting, in older version EL was disabled by default see
http://www.mkyong.com/spring-mvc/modelandviews-model-value-is-not-displayed-in-jsp-via-el/

Post variables from javascript to php

I am trying to send my variables to a php file and I want to prompt before submitting to have the user input his name before submitting. The page won't redirect to the php page as listed below. Any ideas why it is not redirecting? Do I need to include a jquery or some other script source I do not know about
var name = prompt("Enter your name to submit score");
window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves;
also when testing this on the php page with get function it only seems to work if the name variable isn't first. If i have the name,time,moves i get errors.
For sure you have an error on querystring separator. Replace all ? except the first by &
window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves;
As the other guys have mentioned, you need to separate your URI params with an ampersand, not a question mark.
Further, it would be recommended to encode the value that you're receiving from your user, since you never know if they are going to break your code with values you did not expect.
This can be done with the encodeURIComponent method as such:
var name = window.prompt('Enter your name'),
url = 'test.php' +
'?time=' + sec +
'&name=' + encodeURIComponent(name) +
'&moves=' + number_moves;
location.href = url;
Read more about this function on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
*Fixed the time variable to sec from src
First of all, you're not actually posting them as using this code sends them via the GET method. But that's for precision.
Now your problem is most probably that you should write this :
window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves;
Note the & separator between the parameters, where you had a second wrong ?
You only need one question mark. After that the multiple variables should be seperated with the & symbol:
window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves;
Hope this helps!
You have to delimit the query string parameters using & instead of ?.
var name = prompt("Enter your name to submit score"); window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves
IMHO, please consider using the AJAX POST for sending values to server as they are prone to security attacks.
now that you fixed the separators, all the variables passed through the url are considered GET variables so they will be in the $_GET global variable in your php.
To get the variables in the global $_POST variable you would need to use a form with the method set to post or an ajax request that posts them.
HTML
<form id="myform" method="post" action="test.php" method="POST">
<input type="text" name="name" id="nameInput">
<input type="text" name="moves" id="movesInput">
<input type="text" name="time" id="timeInput">
<input type="submit" value="Submit">
</form>
You can still modify the values of the inputs through javascript but you will need to use DOM api methods. There quite a few DOM methods so look through the various references online like the mozilla developers network site
document.getElementById("nameInput").value = "Some Name";
//Though i wouldnt suggest using prompts to get
//data you can still do it
document.getElementById("nameInput").value = prompt("Enter your name");
There are also ways of submitting the form from javascript if needed
document.getElementById("myform").submit();
As for why your page is not changing after changing the href, this is probably due to an error in your javascript which actually makes it so the javascript statement to change the href to not actually execute. You can check for errors by looking in the javascript console.
The console will be in a developer tools window, usually opened by hitting F12 on chrome and IE, firefox and other will have a different shortcut key. If your prompt is showing up, then the error has to be with your string concatenation below it, it will error out if the variables are undefined.
//Will error out because there is no variable someNameVar...
location.href = "test.php?name="+someNameVariableThatDoesntExist;
//in console would see something like
//ReferenceError: someNameVariableThatDoesntExist is not defined
You need to declare sec and number_moves as variables. That's the only problem I see when I tested it.

Categories