document.getElementById doesn't get newly entered HTML text input value - javascript

I use the following code.
The idea is to print the contents of the div with name "PrintThis" which incorporates the text input area "textarea1".
The problem is that getElementById only ever returns the string loaded with the page; "cake" in this case.
If I change "cake" to "pie" by clicking and typing into "textarea1" on the page then printContents still has "cake" not "pie".
<html>
<head> </head>
<script type="text/javascript">
function printFunction(divName) {
var printContents = document.getElementById(divName).innerHTML;
//Now call a script to print (not included)
}
</script>
<body>
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10" style="width:95%!important;" ">cake</textarea>
</div>
<input type="button" value="Print Div" onClick="printFunction('printThis')">
</body></html>
In my production version I also use AJAX to post the text area value back to the server, so could in theory use a page refresh, though that doesn't run, I tried using these options.
document.location.reload(true);
window.top.location=window.top.location;
The production version does have jQuery available too.

first of all you are trying to get innerHTML of the div, instead of the actual textarea.
secondly instead of trying to get innerHTML try using value.
http://jsfiddle.net/qdymvjz8/
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10">cake</textarea>
</div>
<input type="button" value="PrintDiv" onClick="printFunction('textarea1')">
function printFunction(divName) {
var printContents = document.getElementById(divName).value;
}

If you are having multiple items in your div in production then you can iterate through the children of the div and drag out the values.
function printFunction(divName) {
var printContents = document.getElementById(divName),
childItemCount = 0,
stringToPrint = '';
for (childItemCount; childItemCount < printContents.children.length; childItemCount++) {
stringToPrint += printContents.children[childItemCount].value;
}
console.log(stringToPrint);
//Now call a script to print (not included)
}

Related

writing text into the div using document.write

I am trying to add text to two DIVS with ids= DIV1 and DIV2 in a html page(home.html) from a js page main.js using document.write() command. On clicking the button in html page, the respective text must appear in the hmtl page.
The code is as given below. I keep getting an error: document.write can be a form of eval. Is there a possible way of using document.write() and print the text in the div sections.
HTML code:
<head>
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>
</body>
JAVASCRIPT code:
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.write('<div id="div1">'+"Name:"+ arr.name +'</div>');
document.write('<div id="div2">'+"School:"+ arr.school +'</div>');
}
Name:abc
School:pqrst
...using document.write() command
Don't. Only use document.write during the initial parsing of the page, or to write to a new window you've just opened (or better yet, don't use it at all).
Instead, use the DOM. Example:
function xyz(){
var arr = {name: "abc", school: "pqrst"};
addDiv("name", "Name:" + arr.name);
addDiv("age", "School:" + arr.school);
}
function addDiv(id, content) {
var d = document.createElement("div");
d.id = id;
d.textContent = content;
document.body.appendChild(d);
}
<input type="button" value="click!" onclick="xyz()">
If you have an HTML string you want to insert, you can do that with insertAdjacentHTML, but beware of combining text from an object with HTML, because any < or & in the text must be escaped correctly (more than that if you're going to put the content into an attribute, as with your id values). It happens that your two example values don't have those characters, but you can't assume that in the general case.
You can use insertAdjacentHTML() in place of document.write(). Refer this for more details
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="name">'+"Name:"+ arr.name +'</div>');
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="age">'+"School:"+ arr.school +'</div>');
}
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>

issue with using innerHTML() and inserting javascript variable values into HTML

I am working on a small word counter for a school assessment and can't see what is wrong with this code. The idea is when you hit the submit button, it displays "Word Count: " and the amount of character put into a text box. I have showed the teacher my code and he agrees that he doesn't see a problem with it.
Javascript:
window.onload = function(){
var input = document.getElementById(userInput).value;
if(submit.onclick) {
document.getElementById("wordCount").innerHTML = "Word Count: " + input.length;
};
};
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
document.querySelector('#submit').addEventListener('click', function(e) {
const input = document.querySelector('#userInput');
const inputValue = input.value;
const wordsArray = inputValue.split(' ');
document.querySelector('#wordCount').innerText = `Word Count: ${wordsArray.length}`;
})
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
First on window load there is likely no information inside the #userInput, meaning
var input = document.getElementById(userInput).value; will be undefined or ''.
Second, you have no click event bound to your submit button so
submit.onclick will return false;
Binding DOM events
Lastly I switched from using .innerHTML to .innerText as there is no HTML being added into it. Also you your original code was not getting the word count, but would have returned the character count of the input text. To get word count I split the input text on spaces and returned the length of that array as the word count.
Try putting quotes around your userInput inside your getElementById. Right now you're trying to get an element by an ID of undefined because the userInput variable doesn't exist.

how to get textarea input from another HTML page

In a.html:
I have a textarea that is converted into a link after the user clicks the submit button. When the user clicks on the link they are redirected to b.html.
<textarea id="sentenceId">
</textarea>
<br>
<button type="button" id="buttonId" onclick="createLink(document.getElementById('sentenceId').value)">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"></a>
</p>
In b.html:
I would like to display the original text.
In script.js:
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
}
If you want to open a new page and get the text there, you could use a post-form and an input[type="hidden"] to send the text and display it afterwards.
If you wand the link to be sendable, you'd either have to encode the text as get-parameter or save it to a database and add the id of the entry to the link.
As #Kramb already mentioned, localStorage is a possibility, but only if you stay on the same browser and both pages have the same domain.
Using localStorage
The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.
a.html
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
localStorage.setItem("textArea", val);
}
b.html
function getText(){
var textVal = localStorage.getItem("textArea");
}
Another option would be to use a query string.
a.html
function navigateTo(val){
window.href.location = "b.html?text=" + val;
}
This will pass the value of the text from textarea with the url during navigation. Once b.html has loaded, you can do the following.
b.html
function getText(){
var url = window.location.href;
var queryIndex = url.indexOf("=") + 1;
var passedText = url.substring(queryIndex);
document.getElementById('foo').value = passedText;
}
This is possible using JavaScript. You can do an AJAX call to another page on you website, and search for an element to get its content. In you're case an textarea
I wrote an example on codepen.io for you. Click here
To make things simpler im using jQuery in this example.
So how does it work?
First of, include jQuery inside the <head> tag of you're website.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
I created the following structure
structure
root
scripts
jQuery.min.js
index.js
index.html
textarea.html
Contents of index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta -->
<meta charset="UTF-8" />
<title>My New Pen!</title>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<!-- Styles -->
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<button id="clickme">To load the textarea content, click me!</button>
<div id="content">The data from the textarea will be shown here, afte you click on the button :)</div>
<!-- Scripts -->
<script src="scripts/index.js"></script>
</body>
</html>
Contents of texarea.html
<textarea id="textarea">
I am the content of the textarea inside the textarea.html file.
</textarea>
Contents of index.js
(function() {
$(document).ready(function() {
/**
* The button which triggers the ajax call
*/
var button = $("#clickme");
/**
* Register the click event
*/
button.click(function() {
$.ajax({
url: "textarea.html",
type: "GET"
}).done(function(response) {
var text = $(response).filter("#textarea").html();
$("#content").append("<br/><br/><strong>" + text + "</strong>");
});
});
});
})()
So what does index.js do exactly?
As you can see i created an Ajax call to the textarea.html file. The .done function holds the response data. The data inside it can be anything depending on the content of the textarea.html file.
$(response).filter("#textarea").html();
The above piece of code filters out the #textarea div and then gets the innerHTML using the jQuery html() function.
If you want to get the value of the textarea through the [value] attribute, you can replace above line to
$(response).filter("#textarea").val();
I believe you want to do this:
function createLink() {
var textvalue = document.getElementById('sentenceId').value;
document.getElementById("link").innerHTML = textvalue;
document.getElementById("buttonId").className ="hideme";
document.getElementById("sentenceId").className ="hideme";
}
.hideme{
display: none;
}
<textarea id="sentenceId">
</textarea>
<br>
<button id="buttonId" onclick="createLink()">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"/>
</p>

How to show the current user information using javascript?

I have tried to get the user information by id. Its alerting fine.
But I have to print the user information in the html page.
Source:
<html>
<head>
</head>
<body>
<a onclick="GetUserName();" id="user">aaaa</a>
<script language="javascript">
function GetUserName()
{
var wshell = new ActiveXObject("WScript.Shell");
alert(wshell.ExpandEnvironmentStrings("%USERNAME%, %ComputerName%, %USERDOMAIN%"));
}
</script>
</body>
</html>
Output Should be:
<div id="user">User Information: <span id="userinfo"></span></div>
User Information: "user name, computer name, user domain"
How can i print the information in div or others?
You can use innerHTML property, it sets or returns the HTML content (inner HTML) of an element.
HTML:
<div id="user">User Information: <span id="userinfo"></span></div>
Javascript:
document.getElementById("userinfo").innerHTML = wshell.ExpandEnvironmentStrings("%USERNAME%, %ComputerName%, %USERDOMAIN%")
just change the inner HTML of the span. Put below statement in place of alert.
document.getElementById("userinfo").innerHTML = wshell.ExpandEnvironmentStrings("%USERNAME%, %ComputerName%, %USERDOMAIN%");

Why is FileReader.readAsText() returning null?

I am trying to read a file in the same directory of an HTML and JavaScript file however it seems to be returning null. Below I have added the code I have from each file.
HTML File:
<html>
<!-- Code to call the Google Maps API and link style.css sheet -->
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>
<div id="bottom_pane_options">
<button onclick="get_parameters()">Try It</button>
</div>
</div>
</body>
<script type="text/javascript" src="./javascript.js">
</script>
</html>
JavaScript File:
function get_parameters() {
alert("hi"); // Just to let me know the function is getting called
var freader = new FileReader();
var text;
freader.onload = function(e) {
text = freader.result;
}
freader.readAsText('./test.txt', "ISO-8859-1");
text = freader.result; // To my knowledge, this should be taking the current line freader is on and storing it into text
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
test.txt
Iron
Aluminum
Steel
//etc. for x number of times (depends on data I have parsed previously)
All I would like is for JavaScript to read test.txt and parse it into an array (text). The issue is, when I click the button 'Try It', the alert pops up (telling me the function is being called) and text contains null. I am running all files off my computer and all are in the exact same directory.

Categories

Resources