I want to return the value of each input its closest div. Each div has the different name but same div class next to it. The problem is I cannot find the closest div class with jquery. But the value from typing keyup
sent succesfully.
$('.bk_name').on('keyup', function() {
var q = $(this).val();
$(this).parent().closest('div.resp').html(q);
console.log(q);
}); //keyup
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<label>Name1</label>
<input type="text" name="bk_name[1]" />
<div ></div>
</div>
<br />
<div >
<label>Name2</label>
<input type="text" name="bk_name[2]" />
<div ></div>
</div>
For the fiddle here : https://jsfiddle.net/s85n42eo/1/
CodePudding user response:
You can use $(this).next('div.resp').html(q)
or $(this).parent().find('div.resp').html(q)
The problem is that you are using .closest()
it will search for parents, not look for children.
Demo
$('.bk_name').on('keyup', function() {
var q = $(this).val();
console.log($(this).parent().find('')
$(this).next('div.resp').html(q);
console.log(q);
}); //keyup
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<label>Name1</label>
<input type="text" name="bk_name[1]" />
<div ></div>
</div>
<br />
<div >
<label>Name2</label>
<input type="text" name="bk_name[2]" />
<div ></div>
</div>
CodePudding user response:
You should use
.find()
when yo want to search for a nested element.
since you bubble up 1 element using .parent()
you get to the <div >
element. from there you are trying to reach a child element <div >
- you can do that with .find
.closest
traverses up through its ancestors in the DOM tree while
.find
does the opposite
$('.bk_name').on('keyup', function() {
var q = $(this).val();
$(this).parent().find('div.resp').html(q);
console.log(q);
}); //keyup
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<label>Name1</label>
<input type="text" name="bk_name[1]" />
<div ></div>
</div>
<br />
<div >
<label>Name2</label>
<input type="text" name="bk_name[2]" />
<div ></div>
</div>