tags:

views:

102

answers:

1

In order to validate a form like:

<input type="text" name="trueExplain" />
<input type="text" name="true1" />
<input type="text" name="true2" />
<input type="text" name="true3" />
<input type="text" name="true4" />
<input type="text" name="true5" />

in order to validate fields before submit, I want to add an id for each input element:

<input type="text" name="true1" />

becomes:

<input id="true1" type="text" name="true1" />

Then, for each input element, I want to add a label:

<input type="text" name="trueExplain" />
<input type="text" name="true1" />
etc

becomes:

<label for="trueExplain"></label>
<input id="trueExplain" type="text" name="trueExplain" />
<label for="true1"></label>
<input id="true1" type="text" name="true1" />
etc

I need some guidance both in design and implementation with jQuery.

+4  A: 

If you want to do this with jQuery you could use something like for IDs:

$('input[type=text][name^=true"]').each(function () {
    $(this).attr('id', $(this).attr('name'));
});

For labels something like that:

$('input[type=text]').each(function () {
    var label = $(document.createElement('label'));
    label.attr('for', $(this).attr('id'));
    $(this).before(label);
});

But personally I would rather set those IDs and labels in HTML.

RaYell
thanks, it worked like a charm!
dfa