javascriptjqueryhtmljsononload

html - how to fill input text on load?


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 for input tag but ot does not have any effects.

<input type="text" class="form-control" onload="this.value = 'value';" name="company[name]" />

Solution

  • 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" />