Html 输入字段的Javascript设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16101999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:40:40  来源:igfitidea点击:

Javascript set value of an input field

javascripthtmlinputsetattribute

提问by redestructa

Since while I cannot set the value of an input field with type=text. Before, I always used something like this:

因为虽然我无法使用 type=text 设置输入字段的值。以前,我总是使用这样的东西:

<input style="display: none" type="text" name="geo_poi" value="" id="geofeld" />

Then, in JavaScript i added code containing a line like this:

然后,在 JavaScript 中,我添加了包含这样一行的代码:

document.getElementById("geofeld").value = geo_poi;

This always worked. Maybe the new browsers don't want to support the method above anymore.

这总是有效的。也许新的浏览器不想再支持上面的方法了。

回答by redestructa

So using the following method for setting attributes worked fine.

因此,使用以下方法设置属性效果很好。

document.getElementById("geofeld").setAttribute("value", geo_poi);

回答by David Salamon

For situations when setAttribute does not yield any result (think HTML5 user/password input), consider this:

对于 setAttribute 不产生任何结果的情况(想想 HTML5 用户/密码输入),请考虑:

document.getElementById("geofeld").setRangeText("text");

回答by John Johnson

HTML

HTML



<input type="text" placeholder="Item 1" id="item1" />
<input type="text" placeholder="Item 2" id="item2" />



JAVASCRIPT

爪哇脚本



$('#item1').blur(function() {
    var item1var = $('#item1').val();
    $('#item2').val(item1var);
});

Jsfiddle HERE

Jsfiddle在这里