最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Generic way to fill out a form in javascript - Stack Overflow

programmeradmin5浏览0评论

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 wele suggestions that take advantage of it.

EDIT: this is what I've e 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.

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 wele suggestions that take advantage of it.

EDIT: this is what I've e 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.

Share Improve this question edited Dec 28, 2011 at 13:53 munity wiki
3 revs, 2 users 100%
TM.
Add a ment  | 

5 Answers 5

Reset to default 6

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 plicated.

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.

Try this:

Event.observe(window, 'load', function() {
  var loc = window.location.search.substr(1).split('&');

  loc.each(function(param) {
      param = param.split('=');
      key = param[0];
      val = param[1];

      $(key).value = val;
  });
});

The above code assumes that you assign id values as well as names to each form element. It takes parameters in the form:

?key=value&key=value

or

?option1=1&option2=2

If you want to keep it at just names for the elements, then try instead of the above:

Event.observe(window, 'load', function() {
  var loc = window.location.search.substr(1).split('&');

  loc.each(function(param) {
    param = param.split('=');
    key = param[0].split('_');

    type = key[0];
    key = key[1];
    val = param[1];

    $$(type + '[name="' + key + '"]').each(function(ele) {
      ele.value = val;
    });
});

This code takes parameters in the form of:

?type_key=value&type_key=value

or

?select_option1=1&select_option2=2

You said you're already going through the elements and setting the values. However, maybe this is cleaner that what you have?

function setFormSelectValues(form, dataset) {
    var sel = form.getElementsByTagName("select");
    dataset.replace(/([^=&]+)=([^&]*)/g, function(match, name, value){
        for (var i = 0; i < sel.length; ++i) {
            if (sel[i].name == name) {
                sel[i].value = value;
            }
        }
    });                
}

You could then adapt that to more than just select elements if needed.

Three lines of code in prototype.js:

$H(query.toQueryParams()).each(function(pair) {
    $("form")[pair.key].setValue(pair.value);
});

You can get form data in JavaScript object using formManager .

发布评论

评论列表(0)

  1. 暂无评论