English 中文(简体)
Modify javascript code to iterate through all 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
    return 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





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签