Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric way to fill out a form in javascript
    primarykey
    data
    text
    <p>I'm looking for a really generic way to "fill out" a form based on a parameter string using javascript.</p> <p>for example, if i have this form:</p> <pre><code>&lt;form id="someform"&gt; &lt;select name="option1"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;select name="option2"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; </code></pre> <p>I'd like to be able to take a param string like this: <code>option1=2&amp;option2=1</code></p> <p>And then have the correct things selected based on the options in the query string.</p> <p>I have a sort of ugly solution where I go through children of the form and check if they match the various keys, then set the values, but I really don't like it.</p> <p>I'd like a cleaner, <strong>generic</strong> way of doing it that would work for any form (assuming the param string had all the right keys).</p> <p>I'm using the prototype javascript library, so I'd welcome suggestions that take advantage of it.</p> <p>EDIT: this is what I've come up with so far (using prototype for <code>Form.getElements(form)</code>)</p> <pre><code>function setFormOptions(formId, params) { params = params.split('&amp;'); params.each(function(pair) { pair = pair.split('='); var key = pair[0]; var val = pair[1]; Form.getElements(form).each(function(element) { if(element.name == key) { element.value = val; } }); }); } </code></pre> <p>I feel that it could still be faster/cleaner however.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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