html - how to fill input text on load?
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" />
$('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]" />
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