Generic way to fill out a form in javascript

TM. picture TM. · Nov 2, 2008 · Viewed 8.4k times · Source

I'm looking for a really generic way to "fill out" a form based on a parameter string using javascript.

for example, if i have this form:

<form id="someform">
  <select name="option1">
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <select name="option2">
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
</form>

I'd like to be able to take a param string like this: option1=2&option2=1

And then have the correct things selected based on the options in the query string.

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.

I'd like a cleaner, generic way of doing it that would work for any form (assuming the param string had all the right keys).

I'm using the prototype javascript library, so I'd welcome suggestions that take advantage of it.

EDIT: this is what I've come up with so far (using prototype for Form.getElements(form))

function setFormOptions(formId, params) {
  params = params.split('&');
  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;
      }
    });
  });
}

I feel that it could still be faster/cleaner however.

Answer

adgoudz picture adgoudz · Nov 2, 2008

If you're using Prototype, this is easy. First, you can use the toQueryParams method on the String object to get a Javascript object with name/value pairs for each parameter.

Second, you can use the Form.Elements.setValue method (doesn't seem to be documented) to translate each query string value to an actual form input state (e.g. check a checkbox when the query string value is "on"). Using the name.value=value technique only works for text and select (one, not many) inputs. Using the Prototype method adds support for checkbox and select (multiple) inputs.

As for a simple function to populate what you have, this works well and it isn't complicated.

function populateForm(queryString) {
    var params = queryString.toQueryParams();
    Object.keys(params).each(function(key) {
        Form.Element.setValue($("someform")[key], params[key]);
    });
}

This uses the Object.keys and the each methods to iterate over each query string parameter and set the matching form input (using the input name attribute) to the matching value in the query params object.

Edit: Note that you do not need to have id attributes on your form elements for this solution to work.