views:

600

answers:

4

I'm writing a HTML form that's divided in fieldsets, and I need to get the form fields from a specific fiedset in a function.
Currently it's like this:

function conta(Fieldset){  
    var Inputs = Fieldset.getElementsByTagName("input");  
    var Selects = Fieldset.getElementsByTagName("select");  
    /* Doing the stuff I need to do in two iterations, one for each field type */  
}

But who knows what the future may hold, and if the form gets some new field types (radios, checkboxes) this could become awful to mantain.
I know that form elements have the elements attribute that returns all the form fields and I was hoping I could use something like that.
(I know I still gotta discriminate the field type in a bunch of conditionals inside the iteration, but I think it would be faster and easier to keep. Unless it isn't and I should not be doing it)

+1  A: 

Haven't tested this and don't know how it would work, but you could use JQuery here to select all the elements into a JQuery object

//$("input select textarea").each(function() {
$(":input").each(function() { //even better
    // do stuff here
});

this would at least cleanup the code, although you would still have to add conditional statements based on field type like you mentioned.

Ryan Eastabrook
Thanks, but JQuery isn't really an option...
Gabe
it's too bad. It really makes this kind of thing much simpler.
Ryan Eastabrook
jQuery is not that big and you're going to end up writing a lot of code that someone else has already written.
tvanfosson
+1  A: 

@Ryan is on the right track if you want to use jQuery (and I would), but I'd suggest something more along the lines of:

$('fieldset#fieldset1 > input[type=text]').each( function() {
      ... do something for text inputs }
 );

$('fieldset#fieldset1 > input[type=radio]').each( function() {
      ... do something for radios }
 );

$('fieldset#fieldset1 > select').each( function() {
      ... do something for selects }
 );

$('fieldset#fieldset1 > textarea').each( function() {
      ... do something for textareas }
 );

As an improvement over if-then-else constructs.

tvanfosson
+1  A: 

Radio buttons and checkboxes are still input tags and will be in the Inputs var. The problem is, you'll need to add handlers for the checked state to see which radio buttons and checkboxes are selected.

Even worse, you can have more than one radio button and checkbox with the same name... in fact you have to for radio buttons or they don't work as expected.

R. Bemrose
A: 

No jQuery, no problem:

function condat(fieldset) {
    var tagNames = ['input', 'select', 'textarea'];  // Insert other tag names here
    var elements = [];

    for (var i in tagNames)
        elements.concat(fieldset.getElementsByTagName(tagNames[i]);

    for (var i in elements) {
        // Do what you want
    }
}
kRON