html assigning value to input text using javascript does not work - javascript

I am new to programming and I have a small problem
I have a form named "fr" with an input text box named "in" and a variable "n" with the value of "my text"
this is my code what I have:
<html>
<head>
<script LANGUAGE="JavaScript">
var n = "my text";
document.fr.in.value = n;
</script>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
</body>
</html>
but somehow input "in" does not show the text "my text"
I have been browsing the internet but I couldn't find any solution which works..
everything what I try does not work.
I think I am doing something very simple wrong.
please help me.

document.fr does not exist yet at time of invocation; hence, everything following it doesn't exist either, so it throws a TypeError
TypeError: Cannot read property 'in' of undefined
To fix this, move your code to be invoked after the nodes exist, using your favourite method
window.addEventListener('load', function () {
var n = "my text";
document.fr.in.value = n;
});
I'll further note that;
The preferred way to look up an Element is to give it an id attribute and use document.getElementById. An id must be unique.
Using the language attribute of <script> is depreciated, if you want to specify the language, use the type attribute type="text/javascript" or type="application/javascript"
Opening the Console when a script is not working as expected will often show you the cause immediately. This is usually done with F12.

You should init the script after the form is defined, as explained by Paul S. in his answer. So you may do,
<html>
<head>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
<script type="text/javascript">
var n = "my text";
document.forms.fr.in.value = n;
</script>
</body>
</html>
This would run the script after the form is defined. Or put this code in some function, and instantiate the function after the form is defined(i.e. loaded).

As Paul pointed out you should only try to get a hold of page elements when you are certain that the element you are interested has already been loaded. So in this case you can set the value of the input field by running your code when the page has fully loaded and by getting a reference to the input like this:
window.addEventListener("load", function () {
var n = "my text";
var myInput = document.getElementsByName("in");
myInput[0].value = n;
});
Note, because getElementsByName() returns an array, you will have to use [0], to get the first element.

Related

Difficulty with using HTML DOM .createElement(), .setAttributeNode(), and .appendChild() methods

I'm learning how to develop a dynamic webpage and am trying to use HTML DOM to add JS objects but nothing is appearing after several troubleshooting attempts.
I've tried using .createAttribute() instead of .setAttribute() and have carefully read the descriptions of all the methods to make sure I was using them correctly.
<html>
<body>
<div id="greeting_section">
</div>
<script>
let greeting_post = document.createElement("P");
greeting_post = document.setAttributeNode("id","post");
let greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);
</script>
</body>
</html>
I expect it to output "howdy howdy" but nothing appears in my Firefox browser.
It looks like you're overwriting greeting_post. Also, you might just be meaning to use setAttribute instead of setAttributeNode. See below for a working example.
let greeting_post = document.createElement("P");
greeting_post.setAttribute("id","post");
let greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);
<html>
<body>
<div id="greeting_section">
</div>
</body>
</html>
First: When I ran your code the browser console showed this error
Uncaught TypeError: document.setAttributeNode is not a function
That's the first thing you should do when your code doesn't work, Take a look at the browser console.
Second: in your code greeting_post = document.setAttributeNode("id","post"); you are trying to add id="post" to greeting_post variable which is the p tag put you do it wrong, Your code means change the variable greeting_post to a new value document.setAttributeNode("id","post"); which mean Set attribute id="post" to the document.
So, instead of your code, The correct code should go like this:
greeting_post.setAttribute("id","post");
In English this is mean, select greeting_post and set it's attribute to id="post"
So finale, The complete code should be like this:
let greeting_post = document.createElement("P"),
greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.setAttribute("id","post");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);

How to display page title in form field?

I'd like to display the page title in a form input field using plain javascript.
I've tried this but it doesn't work. What am I doing wrong?
<input type="text" value="javascript:document.title;"/>
Also, how can I check if the input field is actually there and do nothing if so. I'd like to do this check to avoid JS errors.
No, it would not. value is never executed. Try this instead:
<title>title text here</title>
<!-- ... -->
<input type="text" id="titleinput">
<script>
var theInput = document.getElementById('titleinput')
if (theInput) {
theInput.value = document.title;
}
</script>
EDIT: Shown how to test for existence of the input, and removed the arcane way of finding title since there is a better way. Although, in this case, you might know that you've created the input field, and take it as granted that it is there (your program should make an error if it's not, just like it should make an error if you delete a line from the code itself. I would only have such a check on HTML that I do not control. It might be a personal choice though, I know I don't do enough defensive programming.
EDIT2: jasonscript has a point, but I thought it would confuse the OP even more. If you want a best-practices answer though, you'd do some variety of this, to avoid global variables:
(function(theInput) {
if (theInput) {
theInput.value = document.title;
}
})(document.getElementById('titleinput'));
value attribute is a string, it wouldn't execute if you place some JS in it.
You would set its value with JS after the input is ready in DOM:
<input type="text" value="">
<script>
document.querySelector('input').value = document.title;
</script>
Whereas querySelector will give you the first input element in the DOM.
Specificly, you can pass any css selectors to the method, e.g. ID selector in following code. Please note different parameter querySelector is using:
<input type="text" value="" id="titleInput">
<script>
document.querySelector('#titleInput').value = document.title;
</script>
More on querySelector, visit selectors api spec.
This would work:
HTML:
<title>awesome site</title>
<input type="text" id="textinput" value=""/>
JAVASCRIPT:
<script>
var title = document.title;
var textinput = document.getElementById('textinput');
if (textinput) {
textinput.value = title;
}
</script>
or shorter:
<script>
document.getElementById('textinput').value = document.title;
</script>

document.getElementById is returning null or undefined everytime

Javascript code is
function addConformationNo(){
var confirmationNo = document.getElementById("addedconfirmation").val();
alert(confirmationNo);
}
and I'm calling addConformationNo() function on click of a button
When the addConformationNo() function is executed, the function call to document.getElementById returns null everytime. Why? Any clues?
Either:
You don't have an element of that id
You are calling the function before the element exists
You are misreading the error message
DOM elements do not have val methods associated with them, so you are likely to get a "Property is undefined or not a function" error, but that is complaining about val not the return value of getElementById.
Access the value property instead.
var confirmationNo = document.getElementById("addedconfirmation").value;
var confirmationNo = document.getElementById("addedconfirmation").value;
will do.
You can also inspect element by right clicking on the browser or you can check the javascript console in your browser.
<html>
<head>
<script type=text/javascript>
function addConformationNo(){
var confirmationNo = document.getElementById("addedconfirmation").value;
alert(confirmationNo);
}
</script>
</head>
<body>
<input type = "text" name = "addedconfirmation" id = "addedconfirmation" />
<input type="submit" onclick="addConformationNo();">
</body>
</html>
If you are getting such a message for every element. Then you may have included the javascript file at the beginning of HTML on the top instead of the bottom.

Onchange Event in Javascript; How to input diffrent items

I am fairly new to javascript and I am 13. So I am new to events in javascript. I would like help on this code:
<head>
<script>
function myFunction()
{
var x=document.getElementById("fname");
if (x=="Kyle")
{
document.write("Correct!");
}
else
{
document.write("Incorrect!")
}
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
</body>
I want it to say correct when I type my name. Please help. Thanks
the line
if (x=="Kyle")
should read
if (x.value=="Kyle")
x represents the element, not the element's value.
I hope this helps. Feel free to ask if you have any other problems.
First create a div tag below your form and give it an id of something like "messageBox"
so:
<div id="messageBox"></div>
then replace
document.write("Correct!");
with
document.getElementById('messageBox').innerHTML = "Correct!";
and the same for incorrect.
All this does is create a div tag so that the javascript has somewhere to output the success/failure message.
You were oh so very close. You get the DOM element (getElementById), but you need to get the actual value of the element. Use x.value == "Kyle"

Javascript Question regarding appendChild

Im just learning javascript and I'm just wondering why this doesn't work. I've created a button and when it is clicked I assigned a function which is supposed to append some text to all my paragraphs. I don't know why it doesn't work:
<html>
<head>
<title>javascript test</title>
</head>
<body>
<script language="javascript" type="text/javascript">
function appendStuff(){
var node = document.getElementsByTagName("P");
node.appendChild.createTextNode('Here's some text');
return true;
}
</script>
<noscript>
Your browser doesn't support javascript.
</noscript>
<input type="submit" value="click me" onclick="appendStuff();" />
<p>
This is the first paragraph.
</p>
<p>
This is the second paragraph.
</p>
<p>
This is the third paragraph.
</p>
</body>
</html>
you should pass new node as argument to appendChild method, like here:
var nodes = document.getElementsByTagName("P");
for(var i=0; i<nodes.length; i++) {
nodes[i].appendChild(document.createTextNode("Here's some text"));
}
document.getElementsByTagName returns a list (array) of element instead of just one, you have to pick up the one you'd like to append (i.e. node[0])
Try this
<html>
<body>
<script language="JavaScript">
function function11() {
var myNode = document.createTextNode("New Text Node");
document.body.appendChild(myNode);
}
</script>
<button onclick="function11();">Create text node</button>
</body>
</html>
function appendStuff(){
var node = document.getElementsByTagName("P");
var txt = 'Here is some text';
var newT = document.createTextNode(txt);
node.appendChild(newT);
return true;
}
Try the above method!!!!
> <script language="javascript"
> type="text/javascript">
The language attribute has been deprecated for over a decade, it should not be used.
> function appendStuff(){ var node = document.getElementsByTagName("P");
> node.appendChild.createTextNode('Here's some text');
> return true;
> }
As others have pointed out, getElemetsByTagName returns a live NodeList, which has a length property and whose members can be accessed by index. Note that while it is array-like, it is not an array.
A text element can be appended to the first node in the NodeList using:
node[0].appendChild(document.createTextNode("Here's some text"));
However it is much safer to first see if node[0] exists before attempting to call one of its methods.
> <noscript> Your browser doesn't
> support javascript. </noscript>
The fact that a browser displays a noscript element doesn't necessarily mean that the browser doesn't support javascript. The description of a noscript element includes:
The NOSCRIPT element allows authors to provide
alternate content when a script is not executed.
W3C, HTML4.01, ยง18.3.1
> <input type="submit" value="click me"
> onclick="appendStuff();" />
An input with a type of submit is intended to be in a form and be used to submit the form. A more appropriate value for the type attribute here is "button". And the XML-style closing tag is unnecessary.
document.getElementsByTagName return 'array' of fetched doms rather than one dom. so you need to specify single dom with for loop of this array or sth likely.

Categories

Resources