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
Share on other sites

It just returns this: 

[prevObject: jQuery.fn.jQuery.init[1], context: li#selected, jquery: "1.9.1", constructor: function, init: function…]context: li#selectedlength: 0prevObject: jQuery.fn.jQuery.init[1]__proto__: Object[0] 
Edited by Freid001
Link to comment
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.