2

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>");
};

5 Answers 5

2

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 *)

Sign up to request clarification or add additional context in comments.

2 Comments

You shouldn't use something.each() if something is not a jQuery object. Use $.each(something, function(idx, obj) { ... }) instead. Besides that, the callback is pretty incorrect since you are't iterating over DOM objects anymore.
You're totally right, I don't know what I was thinking. I've updated my answer. Thanks
1

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.

Comments

1

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

Comments

0

You could make use of jQuery's serializeArray.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.