开发者

Modify javascript code to iterate through all variables in the form

开发者 https://www.devze.com 2022-12-10 19:29 出处:网络
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?

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
    re开发者_StackOverflow中文版turn qstr;
}

complete JS code @ pastie


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/


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('&') : '';
}


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消