Html - how to fill input text at startup?

I have an HTML form in the view, and I need to fill in some input fields using json variables that come from the server. I do not want to write javascript code for each input field, instead I want to access the json variable in the value attribute of the input tag.

I tested the onload for the input tag, but ot has no effects.

 <input type="text" class="form-control" onload="this.value = 'value';" name="company[name]" /> 
+8
source share
4 answers

Here's a solution for Java / JavaScript.

Keep the name of the <input> elements the same as in the JSON data. The idea is to access the <input> using keys from JSON data.

Here is a snippet of working code :

 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" /> 
+3
source

onload event works with the <body> and some other tags, or you can also use window.onload = function(){} see below code example

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 a unique selector, so add the id attribute to the input element.

you can access the whole element using the right selector in the anonymous window.onload event function

UPDATE

proposed 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 
+6
source
 $('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]" /> 
+3
source

Try this solution.

 <input type="text" autofocus> 
0
source

Source: https://habr.com/ru/post/1209948/


All Articles