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
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
Share Improve this question asked May 14, 2013 at 3:02 hrsetyonohrsetyono 4,46414 gold badges49 silver badges80 bronze badges 1- One solution is to read documentation. – user1106925 Commented May 14, 2013 at 3:15
4 Answers
Reset to default 5If 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 ment 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 mon 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.
You can use:
$(this).closest('.row').find('input:disabled').val(fileName);
since closest()
will traverse up through its ancestors in the DOM tree.
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)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745203090a4616444.html
评论列表(0条)