Javascript html - 如何在加载时填充输入文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27664654/
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
html - how to fill input text on load?
提问by hamed
I have an HTML form in the view and I need to fill out some input fields with json variables that come from the server. I don't want to write javascript code for each input field, instead, I want to access json variable in the valueattribute of input tag.
我在视图中有一个 HTML 表单,我需要使用来自服务器的 json 变量填写一些输入字段。我不想为每个输入字段编写 javascript 代码,而是想访问valueinput 标签属性中的json 变量。
I tested onloadevent for inputtag but ot does not have any effects.
我测试onload了input标签事件,但没有任何影响。
<input type="text" class="form-control" onload="this.value = 'value';" name="company[name]" />
采纳答案by Rahul Desai
Here is a pure/vanilla Javascript solution.
这是一个纯/vanilla Javascript 解决方案。
Keep the name of the <input>elements same as in the JSON data. The idea is to access the <input>with the keys from the JSON data.
保持<input>元素的名称与 JSON 数据中的名称相同。这个想法是使用<input>来自 JSON 数据的密钥访问。
Here is the working code snippet:
这是工作代码片段:
const values = {
a: 5,
b: 15
}
const keys = Object.keys(values)
const length = keys.length
for(let i = 0; i < length; i++){
const key = keys[i]
document.getElementsByName(key)[0].value = values[key]
}
<input type="text" class="form-control" name="a" />
<input type="text" class="form-control" name="b" />
回答by Girish
onloadevent is work with <body>tag and some other tags, or you can also use window.onload = function(){}see below sample code
onload事件与<body>标签和其他一些标签一起使用,或者您也可以使用window.onload = function(){}下面的示例代码
HTML
HTML
<input type="text" class="form-control" name="company[name]" id="company_name"/>
JS CODE
代码
window.onload = function(){
document.getElementById("company_name").value = "value";
}
PS: idwill be unique selector so add id attribute in input element.
PS:id将是唯一选择器,因此在输入元素中添加 id 属性。
you can access all element using right selector in window.onloadevent anonymous function
您可以在window.onload事件匿名函数中使用右选择器访问所有元素
UPDATE
更新
suggested by @AlexanderO'Mara
由@AlexanderO'Mara 建议
'onload' is supported by the following HTML tags:
以下 HTML 标签支持“onload”:
<body>, <frame>, <frameset>, <iframe>, <img>, <link>, <script>
And the following Javascript objects:
以及以下 Javascript 对象:
image, layer, window
回答by Vitorino fernandes
$('document').ready(function () {
$('input').val('value')
})
$('document').ready(function() {
$('input').val('value')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="form-control" name="company[name]" />
回答by Dnyanesh_B
Try this solution.
试试这个解决方案。
<input type="text" autofocus>

