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.