0

I have this html code

<div class="sub-middle-column">
  <div class="div-header">Grandsire
    <a "#", class="table-control-focus sub-header-table-focus" id="table-control-focus-t" >abc</a>
    <ul class="table-controls hide side-action-items">
      <li>
        <a data-remote="true" data-box-no="1" class="find_or_add_horse" href="#">Find/Add Horse</a>
      </li>
      <li>
        <a href="go_to_next_horse" data-remote="true">Go to the Next Horse</a>
      </li>
    </ul>
  </div>
  <input type="text" name="search" id="search" class="search_horse">
</div>

on clicking on find_or_add_horse link I want to get the value of the text field using jquery. I tried parent, child and closest but could not get the result. How can I get the value of text field?

$(document).on('click', '.find_or_add_horse', function(){
  // on clicking on find/add horse link I need the value of text field here
});
6
  • try $("#search").val() Commented Apr 9, 2014 at 10:37
  • sheez, i almost hear people typing the answer faster than me Commented Apr 9, 2014 at 10:39
  • @doniyor not only posting the answer, later editing it faster than me... Commented Apr 9, 2014 at 10:41
  • This question is for the very first time on SO. OP searched and didn't find anything here. Even on the internet. Huh... Commented Apr 9, 2014 at 10:43
  • @MiljanPuzović no way Commented Apr 9, 2014 at 10:43

5 Answers 5

2

http://jsfiddle.net/jFIT/pyPtW/

You can use parents to find the root element, then use find on that element to get the input.

console.log($(this).parents('.sub-middle-column').find('.search_horse').val());
Sign up to request clarification or add additional context in comments.

Comments

2

Try this

$(document).on('click', '.find_or_add_horse', function(){
    var value = $('#search').val();
});

JsFiddle

Comments

1

use .val():

 $(document).on('click', '.find_or_add_horse', function(){
       alert($('#search').val());
    });

if you have multiple sub-middle-column div then try this:

 $(document).on('click', '.find_or_add_horse', function(){
       alert($(this).closest('.sub-middle-column').find('.search_horse').val());
    });

1 Comment

@Anton beat you by 49 seconds
0

You can try the code below

$(document).on('click', '.find_or_add_horse', function(){
     var textValue= $('#search').val();
      });

Comments

0

.val(); is for input fields, .text() for other html containers like p, div..

AND dont forget to $.trim(); the input, cos hopefully you dont want whitespaces around the input text

try this:

$(document).on('click', '.find_or_add_horse', function(){
   var inputtextvalue = $.trim($("#search").val());
});

Comments

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.