bob
bob

Reputation: 85

iterate through form elements in javascript/jquery

I am trying to iterate through all form elements with id that begins with a specified prefix and create an xml string with results, but it is getting a bit complicated as forms form input types seem to have different behaviors . Does this functionality already javascript, jQuery or third party jQuery module?

 function fnPreIterate(){                
         var XMLstring;
         $(':input[id*="f1"]').each(function() {             
            XMLstring += (" <" +this.name+ '>' + this.value + "</"  + this.name + "> " );       
        });         
        $('#XMLstring').html("<pre>" + fnEncodeEntities(string) + "</pre>");
};

Upvotes: 2

Views: 7338

Answers (5)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

If you use:

$(this).val() 

instead of

this.value

you'll save a lot of headaches with difference in form elements.

Another way to iterate is to use .serializeArray():

$.each($('#form').serializeArray(), function() {             
            string += (" <" +this.name+ '>' + this.value + "</"  + this.name + "> " );      
        });

Hope this helps. Cheers

PS: To select by prefix, you should do $(':input[id^="f1"]') (use ^ instead of *)

Upvotes: 2

biluriuday
biluriuday

Reputation: 428

What is the problem you are facing? try using $(this) selector in your function instead. something like this $(this).attr('name') and $(this).val()

Upvotes: 0

malko
malko

Reputation: 2382

Using jQuery you should try:

function fnPreIterate(){                
  var XMLstring='';
  $(':input[id^="f1"]').each(function() {             
    var e = $(this), name=e.attr('name'), val=e.val();
    XMLstring += (" <" +name+ '>' + val + "</"  + name + "> " );      
  });         
  $('#XMLstring').html("<pre>" + fnEncodeEntities(XMLstring) + "</pre>");
};

I think it should work

Upvotes: 1

Mark McLaren
Mark McLaren

Reputation: 11540

You could make use of jQuery's serializeArray.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318488

Use $(this).val() to get the value.

Additionally you mixed up XMLString and string which results in your code creating a global variable and failing when it's called a second time.

Upvotes: 1

Related Questions