JQuery closest() returns undefined

时间:2016-02-12 20:54:12

标签: javascript jquery meteor

I am trying to get the value of a hidden input field using str.replace(/([a-z](?=[A-Z]))/g, '$1 ') but undefined is returned instead.

This is the html template:

closest()

I try to read the value of the hidden input type with, which returns undefined:

<div class="content">
    <input type="hidden" value="ABC123" class="imgRef">

    <div class="input-group">
        <input type="text" class="form-control" id="Item1" placeholder="description" value="{{item1}}" name="Item1" required>
        <span class="input-group-btn">
            <button class="btn btn-default btn-fill addField">
                <i class="fa fa-plus"></i>
            </button>
        </span>
      </div>
</div>

2 个答案:

答案 0 :(得分:6)

.closest traverses up in the DOM. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <body> <span id="icon-menu-mobile"> ☰ </span> <div id="panel"> <div class="panelcontent"> Some text here to fill it out </div> <div id="exit"> Click here to exit </div> </div> </body> isn't any of the parents from the object you are clicking. You need to select the parent of that object (which IS one of the parents from that object you click) and than .imgRef.

Also, as @Daniel says in his answer, you need .find('.imgRef') instead of .val().

So :

.value

See Fiddle

答案 1 :(得分:1)

Here's what you want in order to do this by a relative path from your button, without having to add IDs.

Missing template solver/solve, application/solve with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "/home/mariana/Documents/RD-anagram/anagram/app/views"
     $('button').on('click', function(e) {
       var el = $(e.currentTarget).closest('.content').find('.imgRef').val();
       alert(el);
     });