简体   繁体   中英

Jquery closest() doesn't work on elements within different div

I'm trying to use closest() to get <input> element which is in different div. Here's the markup:

<div class="row">
    <div class="span8">
        <input type="text" disabled="disabled" id="image-name">
    </div>
    <div class="span4">
        <input type="file">
    </div>
</div>

Here's the script

$(document).ready(function(){
    $("input:file").change(function (){
       var fileName = $(this).val();
       //Put the file name inside the disabled <input>
       $(this).closest('input:disabled').val(fileName);
    });
});

It doesn't do anything though. I tried changing input:disabled to #image-name but still doesn't work.

Any solution?

Thanks

If you have an id on the other INPUT element, why are you using the closest function? Why not just $('#image-name')? The closest method does not work the way you think. closest always goes up the DOM tree until it finds a match.

Based on the comment to my initial suggestion, you could get DRY by using the more fancy versions of the jQuery event binders:

function handler(e, args) {
    $(e.data.elem).val(fileName);
}

$('input:file').bind('change', { elem: '#image-name' }, handler);
$('#other-input').bind('change', { elem: '#other-field' }, handler);

reusable event handler parameterized using event data constructs.

Because closest travels upwards, not sideways. Just to add, it starts matching the current element as well.

A more generic way is to use closest to find the common ancestor, which is .row , and find the disabled text box from there. You could also do parent , prev and children , assuming the HTML is always that way.

Use closest to get to the root parent , then use find.

$(this).closest('.row').find('input[disabled]').val(fileName);

Try this

Just now noticed your input has ID so you could just do $('#image-name').val(fileName)

You can use:

$(this).closest('.row').find('input:disabled').val(fileName);

since closest() will traverse up through its ancestors in the DOM tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM