Template literals
See original GitHub issueI am trying to render a form-like template as shown below.
This method below works fine, however it is very manual which is not ideal for the form that I will be creating which will have many more text inputs.
document.getElementById("name").value = "<%= name; %>";
document.getElementById("margin").value = "<%= margin; %>";
document.getElementById("mileage").value = "<%= mileage; %>";
I have tried 2 methods to automate my problem:
<% for (var i = 1; i < Object.keys(info).length; i++) { %>
<% let x = Object.keys(info)[i]; %>
<label for=<% x %>><%= x %></label>
<input type="text" id="<= x %>" value="<% info[x] %>" ><br>
<% } %>
This works except for the fact that when I reload the page the local state is preserved and the value of the text input does not return back to info[x]
.
My other method was to loop through through each text input and apply the value as such;
const elementsList = document.querySelectorAll("#id, #name, #margin, #mileage, #max_price, #min_price");
const elementsArray = [...elementsList];
elementsArray.forEach((i) => {
document.getElementById(i).value = `<% info[${i}] %>`
});
However the problem with this is that <% info[${i}] %>
does not format the i
into the template literal, but instead raises SyntaxError: Unexpected token '{'
.
I have read multiple issues similiar to this however none of them seemed to help. Does anyone have any ideas how I might be able to achieve an automated text input with value of the ejs variables without manually writing out each value?
Issue Analytics
- State:
- Created a year ago
- Comments:6 (3 by maintainers)
Given that the persistence of client-side state is a browser issue, and not an EJS issue, it seems like your solution is actually the optimal one.
I have found a solution which is probably not the most ideal but it works.
This renders the inputs and the values on the input, and in the javascript of that page I added
This means that the form is reset to the values passed into the html.
Thank you