Note that there are some explanatory texts on larger screens.

plurals
  1. POBest practice for populating a form?
    text
    copied!<p>I have a an ejs view that contains a form that I need to populate with data so that the underlying record can be edited. I've passed the object containing the data to the view and now see two ways to populate the form and would like some help deciding which one is better.</p> <h3>Option 1 - "server-side" population</h3> <p>I can put the form values directly into the elements like this:</p> <pre><code>&lt;input type="text" id="txtFirstName" name="txtFirstName" value="&lt;%= person.firstName%&gt;" /&gt; &lt;input type="text" id="txtLastName" name="txtLastName" value="&lt;%= person.lastName%&gt;" /&gt; ... etc </code></pre> <h3>Option 2 - "client-side" population</h3> <p>Alternatively, I can return the entire object to the client and then use javascript to populate the form fields like this:</p> <pre><code>&lt;script&gt; var data = "&lt;%=JSON.stringify(person)%&gt;".replace(/&amp;quot;/gi, '"'); var p = eval('(' + data + ')'); populateForm(p); function populateForm (person) { $("#txtFirstName").val( person.firstName ); $("#txtLastName").val( person.lastName ); .... etc } &lt;/script&gt; </code></pre> <p>The benefit of Option 2 is that the function can easily be reused to repopulate the form if new data gets loaded via ajax. It also eliminates any need for escaping the data because its all in a js object already whereas Option 1 would require some type of html encoding and quotes escaping. Option 1, on the other hand works without js.</p> <p>Is there a standard, best practice-y way to do this (and is it one of these options)?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload