Jump to content

.js HELP with parents() / closest()


Freid001

Recommended Posts

Hi, I have this html code:

 

 <div class="names dropdown">
    <input type="text" class="text_form">
    <ul class="dropdown-menu"></ul>
</div>

Some js adds the following after an ajax call: <li id='selected'><a href='#'>Option</a></li> in between the <ul></ul> tags.

 

I then have this js that listens for id='selected' and when clicked I want it to set the value of input to the value select $(this) however it does not do this. It just says undefined. Im not sure why :( PLEASE HELP!  

$( document ).on( "click", "#selected", function() {

   console.log( $(this).parents() );
   
   $(this).closest('input').val( $this.text() );

 });

Thanks

Link to comment
https://forums.phpfreaks.com/topic/292018-js-help-with-parents-closest/
Share on other sites

The .closest() function only looks for parents, not "any nearest" element in the DOM, so to speak. One alternative is to do something like this since the container seems pretty static..

 

 

$(document).on('click', '#select', function() {
var mainContainer = $(this).parents()[1]; //<div class="names dropdown"> -- Index 1, since static.
 
var inputField = $(mainContainer).find('input')[0]; //Index 0, because it's right below the <div> tag.
 
console.log(inputField);
});

 

Obviously it isn't great practise tho, if you had more dynamic content or happened to add/change a field you'd have to change the indexes as well. But assuming that's a pretty static layout (aside from the dynamic <li> tags), it should work just fine.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.