Assuming there is an unknown list of input types in a form, so it can be a mix of many (radios, selects, texts etc..), and when the page refreshes I get a key-value object from the backend that represents the input names and their values, is it possible to set their values easily without knowing the type, or there are cases where just knowing the input name and value is not enough?
For example, the form:
<form id="myform">
<input type="text" name="text1" />
<input type="radio" name="radio1" />
<input type="radio" name="radio2" />
<select name="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
Then the data object from the backend:
{
"text1": "foo",
"radio1": "bar",
"radio2": "hello",
"select1": "world"
}
Then this is the script I made
function setInputs(inputs) {
let inputElement;
for (const [key, value] of Object.entries(inputs)) {
inputElement = document.querySelector(`#myform [name='${key}']`);
inputElement.value = value;
}
}
But will it set all the inputs that are possible to set? Of course some inputs aren’t possible, like type="file"
, but will my setInputs()
function set what’s possible? Or I need to cover more use cases and what I did is not enough?
2
Answers
This is ok for some input types, but not all of them. Instead of assigning
value
on this line of code:I would call function which will do appropriate action:
Checkbox Fields
Checkboxes have 2 states in which we should concern ourselves with:
true
andfalse
. If the server receives a checkbox[name]: value
it is implied that it’strue
that it is checked. Set the checkbox as checked using the.checked
property (see Example A).Example A
Radio Button Groups
The typical layout of radio buttons is as a group of two or more✱ — each having a specific value. A radio button group has a specific behavior in which the user can only check one radio button of said group. In order to ensure this behavior, each radio button of a group shares the same
[name]
(see Example B).✱If there’s only one value to be checked or unchecked, use a checkbox instead.
With the exception of checkboxes, direct assignment to the
.value
property will work.Example B