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]" />
The autocomplete attribute specifies whether a form or an input field should have autocomplete on or off. Autocomplete allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values.
You can achieve this with the following approach: place the <input> in a <label> with position:relative. give the <label> an ::after pseudo-element with position:absolute. set box-sizing of the <input> to border-box.
The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form. Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
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
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]" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With