tags:

views:

89

answers:

3

Hi,

I am new to JQuery.

I have created many textfields,textarea fields in a DIV .inside that div i kept separate divs for every field(which includes a label tag, and the field(text/textarea)) in an orderly manner.

And now i am trying to retrive the label names and the type,size of those fields ,when cliking on save .How can i do so in JQuery

Also i may not know what fields are there after that label may be anything text,textarea etc..Is it possible to find what tag is following label tag??

Here is the html

 <div id="fb_contentarea_col1down21">



 <div id="1">
               <label id="label1">name</label>
              <input type="text" style="width: 200px;" id="input1"/><br/>
               <div id="instr1"/>
           </div>
            <div id="2">
              <label id="label2">address</label>
              <textarea id="input2" style="width: 200px;"/><br/>
              <div id="instr2"/>
          </div>

        </div><!-- End of fb_contentarea_col1down21 -->

<div id="save"><input type="submit" value="Save Form" class="button" id="saveForm"/>

Please suggest me....

+2  A: 
$('#1 label').text(); // gets label contents: "name"

var input1 = $('#1 label').next(); // gets input1
input1.width(); // input1's width: 200
input1.attr('type'); // input1's type: "text"
input1[0].tagName; // input1's tag type: "input" ([0] gets the dom element)

$('#2 label').next()[0].tagName; // input2's tag type: "textarea"
+1  A: 

In addition to sandersa answer to perform an action when the button is clicked you'd do something like this:

$("#saveForm").click(function() {
  // Borrowing code from sandersa's answer
  alert($('#2 label').next()[0].tagName);
});
Mark A. Nicolosi
+2  A: 

(extending on sandersa's answer)

If you used "for" attribute for the labels, then you could get rid of the id on wrapper divs, or the whole wrapper div if its sole purpose was helping to identify the related label.

  <label for="input1">name</label>
  <input type="text" style="width: 200px;" id="input1"/><br/>
   <div id="instr1"/>
  <label for="input2">address</label>
  <textarea id="input2" style="width: 200px;"/><br/>
  <div id="instr2"/>

Then you could write,

$('#save').click( function () {
    $.each(['input1', 'input2'], function (idx, selector) {
        var label = $('label[for=' + selector + ']');
        var input = $('#' + selector);

        alert(label.text());       // label name
        alert(input.width());      // input width
        alert(input[0].tagName);   // tagname
        alert(input.attr('type')); // type attribute
    });
});
Imran