Tutorial :parent > child notation in jquery 1.3



Question:

I am using jquery 1.3 version

<div id='mainPanel'>     <div>          <h3>Head #1 <a href="#"><input type="text" value="Type 1"/> </a></h3>         <div>          <div id="panel_1">            <div class="items">               <div><input type='text' value="0"/></div>               <div><input type='text' value="1"/></div>               <div><input type='text' value="2"/></div>               <div><input type='text' value="3"/></div>          </div>         </div>       </div>       <div>          <h3>Head #2 <a href="#"><input type="text" value="Type 2"/> </a></h3>       <div>          <div id="panel_2">            <div class="items">               <div><input type='text' value="0"/></div>               <div><input type='text' value="1"/></div>               <div><input type='text' value="2"/></div>               <div><input type='text' value="3"/></div>          </div>         </div>       </div>       <div>  </div>  

Now , here i want to access the text box values from head div and need a id i.e. panel_1 and panel_2

so to do that i have written down following code

  $("#mainPanel > div > h3").each(function(index) {            var panelId = $(this).attr('id'); // i.e. panel_1 and all            // parent > child notation          var ele = $(this).next('div > div > div > div').each(function(index){                  alert($(this).children('input').val());      });    });  

Here i am failed to get the result using parent > child notation

HOW CAN I ACCESS H3 > A > INPUT 's value here


Solution:1

The <h3> elements do not contain any <div> elements at all, so that first selector will mess things up. Really there's no need for it to be so complicated:

$('#panel_1 input').each(function() { ...  

will get you all the input elements in "panel_1".

edit â€" an alternative, now that I see what you mean by, "I need an id":

$('div.mainPanel div.items').each(function() {    var containerId = $(this).closest('div[id]').attr('id');    $(this).find('input').each(function() {      var anInput = $(this);      // ...    });  });  

Relying on a rigid container structure seems like a recipe for long-term problems. That's why "class" and "id" values are so useful - the exact markup structure can change, but flexible code can continue to work.


Solution:2

i have replace

$(this).next('div > div > div > div').each(function(index)   

with following

$(this).next('div').find('div > div > div >input').each(function(index)   


Solution:3

So you are given an id and need to find the inputs contained within its panel?

 $('#panel_' + givenId + ' input').each(function() { ...  

or do you need to cycle through all of the panels and get the inputs?


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »