-1

I'm new in JavaScript and I have a problem, it'll be great if someone could help me. I'm trying to write something from one <p> to h4. my code is:

function ok() {
  document.getElementById("out").innerHTML = document.getElementById("name").value;
}
<label id="label">your text is:</label>
<br>
<input type="text" />
<p id="name" style="font-family: 'Courier New', Courier, monospace;"></p>
<button type="submit" id="click" onclick="ok()">click</button>
<h4 id="out" style="font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;"></h4>

but when I'm doing it I get undefined. If someone could help me understand what I'm doing wrong it'll be great.

j08691
  • 204,283
  • 31
  • 260
  • 272
roi
  • 27
  • 1
  • 4
  • 3
    `document.getElementById("name")` refers to your `p` element with `id="name"` - can you elaborate as to how you came to the conclusion that it should have a `value` attribute...? Your `input` element seems to be what you're after, but it's unclear how you got to the idea that it has an `id` at all, let along one that matches the string `name`. – esqew Feb 09 '22 at 20:48
  • Does this answer your question? [How do I get the value of text input field using JavaScript?](https://stackoverflow.com/questions/11563638/how-do-i-get-the-value-of-text-input-field-using-javascript) – Heretic Monkey Feb 09 '22 at 21:00

3 Answers3

2

It is giving undefined because <p> element is empty and you are using .value you need to use .innerHTML so that is why it is returning undefined.

I changed your code a little bit you can see I am fetching values from the input tag and displaying them in p tag and h4 tag.

function ok()
{
document.getElementById("out").innerHTML=document.getElementById("name").innerHTML=document.getElementById("inputname").value;
}
<label id="label">your text is:</label>
<br>
<input type="text" id="inputname"/>
<p id="name" style="font-family: 'Courier New', Courier, monospace;"></p>
<button type="submit" id="click" onclick="ok()">click</button>
<h4 id="out" style="font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;"></h4>
1

You are referencing the wrong element. It's trying to get the value of <p>. But <p> has no value.

The id="name" attribute must be in the input element.

In this way:

<input id="name" type="text"/>
<p style="font-family: 'Courier New', Courier, monospace;"></p>
0

You should give a id to input then receive value of that:

function ok() {
  document.getElementById("out").innerHTML = document.getElementById("input").value;
}
<label id="label">your text is:</label>
<br>
<input type="text" id="input"/>
<p id="name" style="font-family: 'Courier New', Courier, monospace;"></p>
<button type="submit" id="click" onclick="ok()">click</button>
<h4 id="out" style="font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;"></h4>
Arman Ebrahimi
  • 2,035
  • 2
  • 7
  • 20