0

Html

 <div>                                
    <div>
      <input type="text" class="search_input form-control" placeholder="Search..."></div>
      <span>
         <img src="images/btn-reset-search.png" class="clear_text" alt="">
       </span>
 </div>

I want to get the input field when I click on the image having classname: clear_text.

I tried :

 $('.clear_text').parent().prev('input');
1
  • Your code looks fine. Within the click handler, it becomes $(this).parent().prev('input'); Commented Jul 28, 2015 at 11:41

4 Answers 4

2

Try this:

$('.clear_text').on("click", function()
{
    $(this).closest("div").find("input");
});

It navigates to the first parent div(closest("div")) then searches for an input(find("input")) inside it. You can use input:first if you not sure how many inputs the div element may have.

Sign up to request clarification or add additional context in comments.

Comments

2

Solution:

$(document).on('click', '.clear_text', function(){
     var $input = $(this).closest("div").find("input");
     //do whatever you want with $input, $input.val(), $input.addClass(), etc..
});

Comments

0

Try

 $('.clear_text').parent().prev().find('input');

Comments

0

Try the following solution:

$(function(){
  $(".clear_text").click(function(){
    var inputField = $(this).parent().closest('input[type="text"]');
  })
})

OR

$(function(){
  $(".clear_text").click(function(){
    var inputField = $(this).parent().parent().find('input[type="text"]');
  })
})

Here inputField is the required input.

3 Comments

I don't think this will work! You might need to refer .closest()
May i know the reason.
Reson: Updated in first comment look closely at link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.