views:

395

answers:

4

I have the following code that worked fine till now as I decided to add more variables to the form. How can I make this function smart and itterate and pass all the variables in the form?

    function getquerystring(strFormName) {
    var form     = document.forms[strFormName];
    var word = form.clock_code.value;
    qstr = 'clock_code=' + escape(word);  // NOTE: no '?' before querystring
    return qstr;
}

complete JS code @ pastie

A: 

Assuming they are all simple fields, the following should work just fine (didn't test it, though - sorry if it doesn't "compile"):

function getquerystring(strFormName) {
    var qstr = '';
    var form     = document.forms[strFormName];
    var elements = form.elements;
    var first = true;
    for (elem in elements) {
       var word = elem.value;
       var name = elem.name;
       if (first) {
         first = false;
       } else {
         qstr = qstr + '&';
       } 
       qstr = qstr + name + '=' + escape(word);  
    }
    return qstr;
}

Adding info on supporting multiple Element types:

The question only mentioned text fields so I assumed the easier answer would suffice. Wrong!

Glad you're able to use JQuery (which rocks), but for completeness I'll just flesh this out with a bit of info on how to build your own "dynamic form handler".

First, you have to add checking on the class of elem, like so:

   function isCheckbox(o){ return (o && o.constructor == Checkbox) }

and you have to then do something a little different depending on the type of object you are looking at.

For example:

   for (var elem in elements) {
     var value = '';
     var name = elem.name; 
     if (isCheckbox(elem)) {
        value = elem.checked ? 'true' : 'false';
     } else if (isSingleSelect(elem)) {
        var index = elem.selectedIndex;
        if(selected_index > 0) { 
          value = elem.options[selected_index].value;
        }
     }
   }

There may be situations where you have to turn values into something that is meaningful to your app, like in a multiple-select combo box. You could send one name=value pair for each value or roll them into a comma-seperated list or the like - it all depends on your app. But with this approach one can certainly build the "dynamic form handler" that fits their specific needs.

Check out this article for helpful stuff about how to process each form field type: http://www.javascript-coder.com/javascript-form/javascript-get-form.htm

Benjamin Cox
I'm trying this out, will post back shorty.
shaiss
When debugging the post results I get `unidentified` `string` `unidentified`
shaiss
You forgot to var declare elem, you shouldn't use escape fir reasons I commented on above, and the for in loop doesn't do what you think it does.
Mike Samuel
Be warned that if `for (elem in elements)` comes across a radio set, checkgroup, fieldset, or the like, then "elem" will not have the .value or .name properties available... "elem" may very well be an array of other elements or a "non-element"...
Funka
Also agree on the "for in" not working as is suggested. Sorry, my comment didn't reflect that, but the point remains.
Funka
A: 

The issue with your code is that you're only grabbing the clock_code element value, and ignoring the rest. Here's a replacement I wrote up:

function getquerystring(strFormName) {
 var qstr = '', word = '';
 var key = 0;
 var form     = document.forms[strFormName];
 var fields = ['clock_code', 'message', 'type'];

 for (var i = 0; i<fields.length; i++) {
  key  = fields[i];
  word = form[key].value;
  if (qstr && qstr.length > 0) {
   qstr += '&';
  }
  qstr += encodeURIComponent(key) + '=' + encodeURIComponent(word);
 }

 return qstr;
}

Benjamin's approach is a bit more flexible; mine only queries those fields specifically named in the fields array

Funkatron
Thank you, I need to be flexible as differant forms will call on this function. Thank you
shaiss
+1  A: 

Try this

function formToQueryString(form) {
  var elements = form.elements;
  var cgi = [];
  for (var i = 0, n = elements.length; i < n; ++i) {
    var el = elements[i];
    if (!el.name) { continue; }
    if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')
        && !el.checked) {
      continue;
    }
    cgi.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
  }
  return cgi.length ? '?' + cgi.join('&') : '';
}
Mike Samuel
+1  A: 

It looks like you're serializing a form to a querystring? If that's the case, then this is one place where a JavaScript library is really nice.

Each of these will serialize the first form on the page to a querystring.

// ExtJS
var str = Ext.lib.Ajax.serializeForm(Ext.select('form').elements[0]);

// jQuery
var str = $("form").serialize(); 

// MooTools
var str = $$('form').toQueryString();

// PrototypeJS
var str = $$('form')[0].serialize();

You can see some other methods and how they compare at http://jquery.malsup.com/form/comp/

artlung
I am using jquery, so I'll figure out if I can do that.
shaiss
You should be. $('form[name="foo"]') would get a form named 'foo'. If you want to pass in a form name to a function you could do `function serializeForm(formName) { return $('form[name='+formName+']').serialize(); }`
artlung