最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - User text input with an if statement - Stack Overflow

programmeradmin0浏览0评论

I'm new to JavaScript and have run into a challenge (for me). I've looked online for a solution, but to my surprise I couldn't find it. This must have a very basic solution!

The problem: I want JavaScript to execute an if statement based on user input from a text field.

<input id="text_a" type="text;" />
<p id="answer"></p>
<button onclick="myFunction()">Check</button>

<script>
function myFunction()
{
var a=document.getElementById("text_a").vlaue;

if (a=="hello")
  {
document.getElementById("answer").innerHTML="Correct!";
  }
else
  {
document.getElementById("answer").innerHTML="Oops!";
  }
}
</script>

When I try this creation out, no matter what is entered into the text input (even the right answer) the else statement is executed. What am I missing to get the if statement to execute?? Thanks in advance for any and all help

I'm new to JavaScript and have run into a challenge (for me). I've looked online for a solution, but to my surprise I couldn't find it. This must have a very basic solution!

The problem: I want JavaScript to execute an if statement based on user input from a text field.

<input id="text_a" type="text;" />
<p id="answer"></p>
<button onclick="myFunction()">Check</button>

<script>
function myFunction()
{
var a=document.getElementById("text_a").vlaue;

if (a=="hello")
  {
document.getElementById("answer").innerHTML="Correct!";
  }
else
  {
document.getElementById("answer").innerHTML="Oops!";
  }
}
</script>

When I try this creation out, no matter what is entered into the text input (even the right answer) the else statement is executed. What am I missing to get the if statement to execute?? Thanks in advance for any and all help

Share Improve this question asked Mar 23, 2013 at 20:43 NashNash 31 gold badge1 silver badge2 bronze badges 3
  • You misspelled "value", try a=document.getElementById("text_a").value; – faino Commented Mar 23, 2013 at 20:45
  • Thanks so much, though I'm very embarrassed now. lol – Nash Commented Mar 23, 2013 at 21:36
  • This question appears to be off-topic because it is just a typo. – Kuba hasn't forgotten Monica Commented Sep 14, 2013 at 18:25
Add a ment  | 

3 Answers 3

Reset to default 0

First Remove ';' from type attribute

<input id="text_a" type="text" />

and you have spell mistake in value

var a=document.getElementById("text_a").value;

Here is working Example.

You've spelt value wrong:

var a=document.getElementById("text_a").vlaue;

Should be

var a=document.getElementById("text_a").value;

You misspelled value.

var a=document.getElementById("text_a").vlaue;
发布评论

评论列表(0)

  1. 暂无评论