I have been trying to pass a value from an external javascript file to an HTML form with no luck. The files are rather large so I am not sure I can explain it all but ill try.
Basically a user clicks a link then a js file is initiated. Immediately after a new HTML page loads.
I need this value passed to the HTML page in a form field.
Javascript:
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
Afterwards it should be passed to this Form field
HTML Form Field:
<p>Ad Code:<br>
<input type="text" name="adcode" id="adcode"/>
<br>
</p>
Thanks for any help!
Your HTML file needs to reference the JavaScript js file. Have a function in your JavaScript that returns the value that you need. Use JavaScript (I like jQuery) to set the form field to what you need.
JS file:
<script>
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
function GetDivElement() {
return divElement();
}
</script>
HTML file:
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
document.getElementById('adcode').value = GetDivElement();
}
</script>
Although, really, this might do what you want (depending on what you are trying to do):
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
GetDivElement();
}
</script>
Can it be this?:
function divElement(divCode){
return divCode;
}
divElement(document.getElementById('adcode').value);
Related
in my site i have google reCaptcha component which allows me to specify a callback function inside the attribute "data-callback".
this is my html file:
<html>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
var txtClientResponse = document.getElementById('txtClientResponse');
var txtServerResponse = document.getElementById('txtServerResponse');
function successCallback(value) {
this.txtClientResponse.value = value;
this.txtServerResponse.innerText.clear();
}
</script>
<body>
<div class="g-recaptcha" data-callback="successCallback" data-error-callback="errorCaptcha" data-sitekey="xxxxxx" />
<input ID="txtClientResponse" />
<input ID="txtServerResponse" />
</body>
Everything works great except the fact that i can not access the local variable txtClientResponse, that holds a DOM element, from the callback function "successCallback". to local variables like var test = 1, i can access using this.test.
i tried to pass the "this" using like i am doing on Angular but it didn't work. i need a pure javascript solution - not angular:
<div class="g-recaptcha" data-callback="successCallback.bind(this)" data-error-callback="errorCaptcha" data-sitekey="xxxxxx"/>
I didn't use pure JavaScript for long time because i am using Angular, i forgot that the script tag with the javascript code should be at the very bottom of the body tag content or at least to assign the variables with the getElementById inside the document.onreadystatechange event.
The problem was that the lines:
var txtClientResponse = document.getElementById('txtClientResponse');
var txtServerResponse = document.getElementById('txtServerResponse');
executed before the HTML elements where ready.
Here is the fix for users that may find this question using google
<html>
<body>
<div class="g-recaptcha" data-callback="successCallback" data-error-callback="errorCaptcha" data-sitekey="xxxxxx" />
<input ID="txtClientResponse" />
<input ID="txtServerResponse" />
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
var txtClientResponse = document.getElementById('txtClientResponse');
var txtServerResponse = document.getElementById('txtServerResponse');
function successCallback(value) {
this.txtClientResponse.value = value;
this.txtServerResponse.innerText.clear();
}
</script>
</body>
</html>
I have a login.js which has a function which is called when the clickme button in the HTML is pressed.
document.getElementById('clickMe').addEventListener('click',execuateAllCode);
The line below is in the function that is called by the clickme button and it does not work
var password = document.getElementById("password").value;
It gives this error:
Uncaught TypeError: Cannot read property 'value' of null
popup.html contains this code:
...
<input id="clickMe" type="button" value="clickMe"/>
<input type="password" name="password" id="password" value="temppassword" placeholder="Password"/>
...
The error should mean that there is no element that contains an id="password". But I do have something with that id. Can the function in login.js not "see" the input in the HTML file?
EDIT 1:
I have tried to add:
window.onload = function() {
execuateAllCode()
};
To the .js file, but this does not get rid of the error, it also causes errors in other parts of the code and stops the styling.
The HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<input id="clickMe" type="button" value="clickme"/>
<script language="javascript" src="login.js"></script>
<input type="text" name="email" id="username" value="user#email.com" placeholder="Email"/>
<input type="password" name="password" id="password" value="temppass" placeholder="Password"/>
</body>
</html>
login.js:
document.getElementById('clickMe').addEventListener('click',execuateAllCode);
function execuateAllCode() {
document.write("<br />" + "From login" + "<br />");
var output;
output = FunctionOne();
document.write("<br /> the output: " + output + "<br />");
}
function FunctionOne(){
...
var password = document.getElementById("password").value;
var user_name = document.getElementById("username").value;
...
}
Your are fetching that element which not loaded yet(DOM is not loaded). That's why you are facing the issue.
window.onload = function() {
/*Do that stuff in this function*/
};
For more reference check this link.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
Hope this will help :)
Your popup.html is not the page that includes login.js - that's why code in login.js does not find a DOM element with id="password". The page that includes login.js contains, however, a button with id="clickMe".
After seeing your execuateAllCode:
http://www.w3schools.com/jsref/met_doc_write.asp - "The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML." Add a div element where you put any output using innerText or innerHTML instead of using document.write.
What you need to do is :
Initialize variable password outside the function and then declare it
Or you can use window.onload = function_Name;
Why don't you call function on login button click or any event ?
A great way to debug javascript is warping your variables and events in a console.log and checking their result in the browser console.
Try adding console.log(password) right after you set it equal to the value of the input. This will tell you if that jQuery functionality is working. That will help you find out what the HTML is "seeing"
Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;
I want to POST form values and display them on another html page using Javascript. No server-side technology should be used. I have a function that posts the values but to read the values to another html page, I think I am missing something. Below is the code.
Any help? Thanks in advance.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function post_to_page(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "formresult");
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('target.htm', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
}
</script>
</head>
<body>
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</div>
</form>
</body>
</html>
Here is a simple example of moving data from one Window to another
<!-- HTML -->
<textarea id="foo"></textarea><br/>
<input id="bar" value="click" type="button"/>
and the real code to make it work, which assumes you pass the same origin policy
// JavaScript
var whatever = 'yay I can share information';
// in following functions `wnd` is the reference to target window
function generateWhatever(wnd, whatever) { // create the function actually doing the work
return function () {wnd.document.getElementById('foo').innerHTML = whatever};
} // why am I using a generator? You don't have to, it's a choice
function callWhenReady(wnd, fn) { // make sure you only invoke when things exist
if (wnd.loaded) fn(); // already loaded flag (see penultimate line)
else wnd.addEventListener('load', fn); // else wait for load
}
function makeButtonDoStuff() { // seperated button JS from HTML
document
.getElementById('bar')
.addEventListener('click', function () {
var wnd = window.open(window.location); // open new window, keep reference
callWhenReady(wnd, generateWhatever(wnd, whatever)); // set up function to be called
});
}
window.addEventListener('load', function () {window.loaded = true;}); // set loaded flag (do this on your target, this example uses same page)
window.addEventListener('load', makeButtonDoStuff); // link button's JavaScript to HTML when button exists
You can't get POST values using JavaScript. You can use GET method to pass values.
If you are using html5 you can use localStorage. Otherwise a query string or cookies are your other options.
You said you didn't want the server involved...why are you calling submit?
[Edit]
#Paul S's comment/answer looks very helpful. But you might look at something like the jQuery PostMessage plugin if you need it to be cross browser compatible.
http://benalman.com/projects/jquery-postmessage-plugin/
You don't require a POST request to send data from one page to another. Simply use LocalStorage to do the trick. Just call a Javascript function on form submission. This may help:
HTML:
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</form>
Javascript:
function post_to_page() {
localStorage.value = "Your content here";
window.location = "nextpage.html";
}
This will save the data locally and go to the next page. In the next page, simply call this function to retrieve the stored data:
function get_stored_data() {
alert(localStorage.value);
}
You can simply assign it to a div, textbox other Javascript variable.
Because of a Flex bug uploading files in a secure environment, I'm attempting to hack together a workaround for this in javascript.
To do so, I'm attempting to create a hidden form in javascript, to which I'll attach a file and some xml meta data, then send it to the server in a multipart form post. My first thought is to get this to work in HTML and then port this javascript code into my Flex project.
My first problem is attaching the file to the hidden form in javascript. I'm doing something wrong here. I'm pretty inexperienced with javascript so if there's a better way to do this, I'm eager to learn.
Here's the code I'm current playing with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hidden form post demo</title>
</head>
<body>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
submitForm.enctype = "multipart/form-data";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, inputType, elementName, elementValue) {
var inputElement = document.createElement("INPUT");
inputElement.name = elementName;
inputElement.type = inputType;
try {
inputElement.value = elementValue;
} catch(err) {
alert(err.description);
}
inputForm.appendChild(inputElement);
return inputElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
var selectedFileElement = document.getElementById("selectedFile");
var selectedFile = selectedFileElement.files[0];
createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
submitForm.action= "my url";
submitForm.submit();
}
</script>
<div id="docList">
<h2>Documentation List</h2>
<ul id="docs"></ul>
</div>
<input type="file" value="Click to create select file" id="selectedFile"/>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
</body>
</html>
You can see, I have a try/catch block in createNewFormElement. An exception is being thrown there, but the message says "undefined".
In FireBug, I can see that the elementValue is set to a File object, so I'm not really sure what's going on.
For security reasons, you cannot set the value attribute of an input[type=file]. Your current code doesn't need JavaScript, and can be written using pure HTML:
<form method="post" enctype="multipart/form-data" action="myurl">
<input type="file" value="Click to create select file" name="selectedFile" />
<input type="hidden" name="xml" value="my xml" />
<input type="submit" value="Click to create form and submit" />
</form>
If you want to, it's possible to dynamically add additional non-file form elements, by binding an event to the onsubmit handler.
<form ... onsubmit="addMoreinputs();" id="aForm">
...
<script>
function addMoreInputs(){
var form = document.getElementById("aForm");
// ...create and append extra elements.
// once the function has finished, the form will be submitted, because
// the input[type=submit] element has been clicked.
}
add
var dom=document.getElementById("formdiv");
dom.appendChild(submitForm);
in your createFormAndSubmit function.
and add <div id="formdiv" /> on your page.