html - how to fill input text on load?
Solution 1
Here is a pure/vanilla Javascript solution.
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.
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" />
Solution 2
onload
event is work with <body>
tag and some other tags, or you can also use window.onload = function(){}
see below sample code
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: id
will be unique selector so add id attribute in input element.
you can access all element using right selector in window.onload
event anonymous function
UPDATE
suggested by @AlexanderO'Mara
'onload' is supported by the following HTML tags:
<body>, <frame>, <frameset>, <iframe>, <img>, <link>, <script>
And the following Javascript objects:
image, layer, window
Solution 3
$('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]" />
![hamed](https://i.stack.imgur.com/RT0Q3.jpg?s=256&g=1)
hamed
Web developer with Java Spring MVC. Familiar with php yii framework. Very interested in Object Oriented design and OO design patterns. Client side programmer with angular, javascript and jquery.
Updated on June 07, 2020Comments
-
hamed about 4 years
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
value
attribute of input tag.I tested
onload
event forinput
tag but ot does not have any effects.<input type="text" class="form-control" onload="this.value = 'value';" name="company[name]" />
-
Alexander O'Mara over 9 years
onload
is supported by other tags thanbody
.input
isn't one of them though. -
Alexander O'Mara over 9 yearsUnfortunately, the accepted answer on that question is outdated. The second answer looks more-accurate. Might be simpler to say,
input
does not supportonload
. +1 anyway.