Home > Software engineering >  why I get undefined value instead my input value
why I get undefined value instead my input value

Time:02-10

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.

CodePudding user response:

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>

CodePudding user response:

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>

CodePudding user response:

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>

  •  Tags:  
  • Related