Klav Klav - 3 months ago 8
HTML Question

jQuery Inconsistent text() val() selection and populating input

$name
and
$id
are only copied properly a small portion of the time. Selection is expected to populate the input
#user_search
but selections come up undefined. The text is copied properly at what seems like random...

HTML

<input type="text" name="user" id="user_search" autocomplete="off"
class="user_live form-control" data-parsley-required="true" value="" />
<div id="user_result"></div>


HTML Added to DOM

<div id="user_result" style="display: block;">
<div class="showResult row">
<div class="box-body">
<a class="user_id" id="353">
<div class="col-lg-3 col-md-3 col-xs-3">
<img height="50px" src="/assets/user_1.jpg">
</div>
<div class="col-lg-9 col-md-9 col-xs-9">
<span class="name">First Last</span>
</div>
</a>
</div>
</div>
<div class="showResult row">
<div class="box-body">
<a class="user_id" id="200">
<div class="col-lg-3 col-md-3 col-xs-3">
<img height="50px" src="/assets/user_2.jpg">
</div>
<div class="col-lg-9 col-md-9 col-xs-9">
<span class="name">First Last</span>
</div>
</a>
</div>
</div>
</div>


JS

$('#user_result').on('click',function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').text(); //removed .html($name)
alert($name);
$('#user_search').val($name);
});

Answer

The issue lies with e.target and .find() not working quite right with that layout. Try this:

$('#user_result').on('click',function(e){ 
    var $name  = $(e.target).closest('.showResult').find('.name').text();
    alert($name);
    $('#user_search').val($name);
});

https://jsfiddle.net/feab9ms0/

Comments