Trying to make sense of [object HTMLCollection] From JavaScript .innerHTML Right Function? - javascript

I'm a newcomer to JavaScript. I'm trying to get what I thought would be a simple "onchange" event to work with an input form element and have a JavaScript function write back the value of the input using .innerHTML.
Here is what my output looks like:
First Name *
Hello [object HTMLCollection]
How do I deal with a variable returning the message of "[object HTMLcollection]" Please be explicitIn answering, because as I said, I'm a newcomer to javascript.
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>onchange event Testing input text</title>
<script type="text/javascript">
<!--
function write_firstname()
{
var fnid = document.getElementById("fnm");
var fn = document.getElementsByName("first_name");
fnid.innerHTML = "Hello " + fn;
}
//-->
</script>
</head>
<body>
<form>
<!---->
<label for="first">First Name *</label>
<br />
<div class="form_indent">
<input id="first" type="text" name="first_name" onChange="write_firstname();" autofocus>
<p id="fnm"></p>
<br />
</div>
<!---->
<!---->
<div class="form_indent">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</div>
<!---->
</form>
</body>
</html>
I know it's probably something simple. Someone please kick me in the right direction!

document.getElementsByName("first_name"); returns a collection of elements matching the selector, a nodeList.
Note the s in getElements... everytime you see that, there's a chance more than one element could match, and a nodeList is returned instead of a single DOM node.
A nodeList is an array-like object containing the elements, so you're trying to add an object to a string, and as that's not really possible, javascript runs toString() to turn the nodeList into a string, and the string representation is [object HTMLCollection]
What you could be doing instead is just passing the element to the function
<input id="first" type="text" name="first_name" onchange="write_firstname(this);" autofocus>
and then do
function write_firstname(elem) {
var fnid = document.getElementById("fnm");
fnid.innerHTML = "Hello " + elem.value;
}
FIDDLE

Related

Is it possible to use the submit function to save textareas to a new file?

I am trying to see if it is possible to use a script to write two text areas to a single file when clicking "Submit" on my page? (For total context, these are HTML pages being hosted locally on the machine and are not being housed on a server anywhere)
I successfully learned to erase the two text areas with javascript:eraseText and having that button set the values to "".
I have been looking for an option but I don't know if I'm asking it the right way.
Any help is appreciated.
Edits for clarity
<!DOCTYPE html>
<html>
<head>
<script>
function eraseText() {
document.getElementById("one").value = "";
document.getElementById("two").value = "";
}
function submit() {
}
</script>
</head>
<body>
<div id="boxes">
<textarea id='one' rows="20" cols="70">
</textarea>
<p></p>
<textarea id='two' rows="20" cols="70">
</textarea>
</div>
<p></p>
<input type="button" value="Clear" onclick="javascript:eraseText();">
<input type="button" value="Submit" onclick="javascript:submit();">
</body>
</html>
So I'd like to click submit and have the values in "one" and "two" parsed to a single HTML output.
<!DOCTYPE html>
<html>
<head>
<script>
function eraseText() {
document.getElementById("one").value = "";
document.getElementById("two").value = "";
}
function submit() {
var combined = "";
combined += document.getElementById("one").value;
combined += document.getElementById("two").value;
document.getElementById("destination").innerHTML = combined;
}
</script>
</head>
<body>
<div id="boxes">
<textarea id='one' rows="20" cols="70">
</textarea>
<p></p>
<textarea id='two' rows="20" cols="70">
</textarea>
</div>
<p id="destination"></p>
<input type="button" value="Clear" onclick="eraseText();">
<input type="button" value="Submit" onclick="submit();">
</body>
</html>
The solution that doesn't use any server-side code to accomplish this, if I understand your question correctly, is as follows.
Let's write what your HTML probably currently looks like.
<textarea></textarea>
<textarea></textarea>
<button type="submit">Submit</button>
Let's first add an output area where the preview will appear. This could be a <div></div> element.
Now, add id attributes to all the elements (I'll use the IDs "a", "b", "c", and "d", and the output DIV. This allows JavaScript code to easily grab a certain element using the Document Object Model.
Once done, this is the code
document.getElementById("d").addEventListener("click", function(){ // do this when element with id `d` is clicked
document.getElementById("c").innerHTML = // set the output element's inner HTML to...
document.getElementById("a").value + document.getElementById("b").value
})
<textarea id="a"></textarea>
<textarea id="b"></textarea>
<div id="c"></div>
<button id="d">Submit</button>
document.getElementById(IDGOESHERE) returns a JavaScript object representing the element with that ID. .addEventListener binds something to an event happening (in this case, the click event triggers a function to be called).
That function takes the values of the two textareas, and adds (joins) them together using the + operator, which concatenates with strings.
It then assigns this HTML using the .innerHTML property of the output element.
I'm not sure if this is what you wanted, so please do clarify if it isn't.

html sending parameters to function from id

I'm an absolute beginner and tried to find similar questions but couldn't. Apologies if this has been answered previously.
In my assignment we need to create a form with 2 text fields and 1 button. The fields are for height and width and the idea is that onclick on the button will send the 2 parameters to a function that will change the height + width attributes for a photo. I know I'm doing something wrong because the picture simply disappears. Ideas? Thanks!
<html>
<head>
<script>
function borderResize(height1, width1)
{
document.getElementById('Amos').height = height1;
document.getElementById('Amos').width = width1;
}
</script>
</head>
<body>
<img src="Amos.jpg" id="Amos" />
<form>
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" value="click!" onclick="borderResize('height.value', 'width.value')"/>
</form>
</body>
</html>
When you write
onclick="borderResize('height.value', 'width.value')"
in means that on click borderResize function will be invoked with two string arguments, literally strings "height.value" and "width.value". In your case you want something like this
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
In above case you are selecting element from DOM using getElementById method and then read its value property.
You should learn to use addEventListener(), I would recommend you not to use ugly inline click handler.
The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on.
Here is an example with your code.
window.onload = function() {
document.getElementById('button').addEventListener('click', borderResize, true);
}
function borderResize() {
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}
<img src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/s200x200/11034289_10152822971918167_2916173497205137007_n.jpg?oh=71de7a46a75a946cf1d76e5ab10c1cdc&oe=55889977&__gda__=1434173455_6127f174627ed6014c84e562f47bc44c" id="Amos" />
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" id="button" value="click!" />
However as for your immediate problem you can use
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
onclick="borderResize('height.value', 'width.value')"
here you pass to borderResize strings: 'height.value', 'width.value'.
You may get value of input from function:
function borderResize(height1, width1)
{
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}

How to send information from HTML <input> element to <span> using JavaScript .innerHTML?

I'm very new to JavaScript and trying to mimic an example in a book I'm reading. I would like to take what is input to a HTML element and send the data to a element using .innerHTML. I don't know what is wrong.
<!DOCTYPE html>
<html>
<head>
<title>JS Form</title>
</head>
<body>
<form id="date">
<table>
<tr><td><input type="text" name="user" placeholder="Please input name" onchange="greeting();"></td>
</tr>
<tr><td><span id="hello"></span></td>
</tr>
</table>
</form>
<script type="text/javascript">
function greeting() {
var user = document.date.user.value;
var hello = document.getElementById("hello");
hello.innerHTML = "How are you " + user;
}
</script>
</body>
</html>
Add name="date" to your form tag like below. Else document.date.user.value will not work.
<form id="date" name="date">
Another way to get around the issue, is accessing the date property of the window object.
window.date.user.value;
This is possible because you've set an id on the form.
Or you might consider accessing the form using its id and then get user value as follows:
var user = document.getElementById("date").user.value;
For simplification, and depending on your browser, you could use document.querySelector. Take a look at this very helpful SO post:
JavaScript: how to get value of text input field?
you should do this first:
var user= document.getElementsByName("user");
var hello = document.getElementById("hello");
hello.innerHTML = "How are you " + user[0].value;

place value into input box from query string not working

how can I take the value of a query string and place it into an input box? Currently I have:
<input type="text" name="spouse" id="spouse" value="<script type="text/javascript">
document.write("Name: " + Request.QueryString("spouse"));
</script>"/>
But that only takes the script take and all of its contents and places it into the input box.
I would like to be able to take my query string that is coming from this code:
<tr >
<td><input type="text" name="n1" value="Duck, Donald" /></td>
<td><input type="text" name="n2" value="Daisy" /></td>
<td><input type="button" value="Show" title="Show"
onclick="location.href='example123.html?name=' + escape(this.form.n1.value)+ '&spouse=' + escape(this.form.n2.value);" />
</td>
and have the value for name or spouse appear inside of an input box. What is the proper way to place a value into an input box from a query string?
Request.QueryString is not a native JavaScript function. Use the document.location object and parse out the value you want.
Perhaps use the onload function to perform the action you need. This calls your function once the document has been fully loaded and so you know all tags in the html will exist at this point and be can be referenced properly.
eg.
<html>
<head>
<title>Value Setting</title>
<script type="text/javascript">
window.onload = (function() {
document.getElementById('spouse').value = "one way";
document.forms[0].elements[1].value = "another way";
/* note elements refers to only input children */
});
</script>
</head>
<body>
<form id="myform">
<div>
<input id="first-field" value="first-field" onchange="this.value += ' an example';"/>
</div>
<div>
<p>
<input id="spouse" value="spouse"/>
</p>
</div>
</form>
</body>
</html>
You can't embed elements in attributes as that isn't valid html. Though some attributes can get evaluated as javascript. Namely attributes such as action, onchange, onclick and so on.

Error when trying to refer to a field by name

I am getting an error (document.my_formm.fieldName.value is null or not an object) from the below code:
<html>
<head>
<title>(Type a title for your page here)</title>
<script language=JavaScript>
function check_length(my_formm,fieldName)
{
alert(fieldName);
alert(document.my_formm.fieldName.value);
}
</script>
</head>
<body>
<form name=my_form method=post>
<input type="text" onChange=check_length("my_form","my_text"); name=my_text rows=4 cols=30 value="">
<br>
<input size=1 value=50 name=text_num> Characters Left
</form>
</body>
</html>
Your check_length function is using variables to identify the form and field names, however, by using dot notation, you are referring to a element of document named my_formm. When you are are using variable names, you should use the bracket notation instead:
function check_length(my_formm,fieldName)
{
alert(fieldName);
alert(document[my_formm][fieldName].value);
}
Also, you should really quote attributes in your input:
<input type="text" onKeyPress="checkCompanyName();" onChange="check_length('my_form', 'my_text');" name="my_text" rows="4" cols="30" value="">
In your javascript you have referred to the form as 'my_formm' i.e. you have an extra 'm' at the end which is not present in the HTML, this could be your problem.
Why does your JavaScript method take in that first parameter if it never uses it?
Just do onChange=check_length(this)
and in your function
function check_length(element)
{
// element points to the element in question
// element.form points to the form if you need it
alert(element.value);
}
In general it would be nice to write WHAT error are you getting...
anyhow checkCompanyName is not defined in the code you wrote.
Also you're passing two strings as variable, they do not have properties...
A better way to do this:
<script type="text/javascript">
function checkLength()
{
inp = document.getElementById("myInput");
len = document.getElementById("len");
len.value = inp.value.length;
}
</script>
<input id="myInput" onkeyup="checkLength()" />
<input id="len" />
EDIT AFTER COMMENT:
<script type="text/javascript">
function checkLength(inputname, lenname)
{
inp = document.getElementById(inputname);
len = document.getElementById(lenname);
len.value = inp.value.length;
}
</script>
<input id="myInput" onkeyup="checkLength('myInput', 'len')" />
<input id="len" />
document.my_formm looks for a form named my_formm. You need to use the associative array sintax instead, like document[my_formm], which will pass the value in my_formm at runtime, rather than looking for a property in the document object called my_formm (which doesn't exist).

Categories