使用java脚本为文本框分配值

时间:2013-09-22 08:14:55

标签: javascript html

我只是一个简单的问题。

我想为文本框分配一个值,但不像Java脚本函数那样为字符串赋值。

我将举一个简单的例子:

     <input type="text" value="exam">//  here i assign the value as a string .





    <input type="text" value=functionx() >  // functionx is a java script function that        
          will assign a value to the text box.

     <script > function functionx(){return 'exam';}</script>

现在在这个简单的例子之后,我的问题是:如何使用java脚本函数为文本框分配值?

1 个答案:

答案 0 :(得分:5)

您需要在脚本中指定它,不能在html的value属性中调用函数。

试试这个:

var text = document.getElementsByTagName('input')[0]; // would be better if you have a ID
text.value = functionx();

演示here

我的建议是在输入中提供id(例如<input id="input_id" type="text" value="exam">),然后在我的示例中使用getElementByID

在这种情况下,它可能看起来像this demo

相关问题