manoj manoj - 1 month ago 9
Javascript Question

How to get current element in jquery autocomplete?

I'm using jQuery autocomplete.
I have 10 text boxes in my page.I binded autocomplete using class name.
In source method I'm calling a service to get the data based on user entered value.I need to pass 2 parameters to service.
1. user entered value.
2. data that is storing in the parents of textbox.

How can I get it?

<div data-id="101">
<input class="search_txt" type="text"/>
</div>
<div data-id="102">
<input class="search_txt" type="text"/>
</div>
.....
...
...
....
$('.search_txt').autocomplete({
minLength: 1,
source: function(request, response) {
//service here
//need to get "data-id" of current using text box.
},
focus: updateTextBox
select: updateTextBox
});


Thanks in advance.

Answer

If i were understood right, use this:

$('.search_txt:focus').parent().attr('data-id')

it will get input that is focused with class name .search_txt then select it's parent, and get attribute of data-id

Example:

$('.search_txt').autocomplete({
      minLength: 1,
      source: function(request, response) {                                              
        console.log("Data-id: "+$('.search_txt:focus').parent().attr('data-id'));   
        //service here 
       //need to get "data-id" of current using text box.
      }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div data-id="101">
    <input class="search_txt" type="text"/>
</div>
<div data-id="102">
   <input class="search_txt"  type="text"/>
</div>

Comments