1

I am working with searching string from database and selected string appending to the text box

I can get the search results from database and i can append the result below the textbox.

But my problem is onclick of particular result I can't get the "id" of appended result

My code looks like this..

<span id="new">
    <input id="addSearch" type="text" width="50px"/>
</span>

<div id="append" style="margin-top: -11px;width: 149px;"></div>

<script type="text/javascript">

$(function(){      
  $("#addSearch").keyup(function() {    
    var v = $('#addSearch').val();
    $.getJSON('http://localhost/api/getresult/?q='+v, function(data){
      $('#append').html('');
        $.each(data, function (key,value){
           $('<div  id='+value["id"]+' class="searchResult">  
                   '+value["name"]+' 
                 </div>').appendTo($('#append'));
         });
     });    
  });    
});
$('.searchResult').click(function(){
  alert($(this).attr("id"));
});

6 Answers 6

2

Your key up method is correct, you just need to modify the click event like this:

$(document).on('click', '.searchResult', function(e) {
    alert($(this).attr('id'));
});​
Sign up to request clarification or add additional context in comments.

1 Comment

Note that you can limit the scope of the event handler by binding it to $('#append') instead of $(document).
1

As Adarsh Raj noted, you are not binding the click handler on the .searchResult elements you append in the AJAX callback. jQuery collections are not "live" and as such, the event handler is directly bound on the matching DOM elements at the time of the call.

However, instead of manually binding the handler to each inserted element, you should use a delegated event handler on a parent element:

$('#append').on('click', '.searchResult', function(){
    alert($(this).attr("id"));
});

This requires that the #append element is in the DOM at the time of the call, but any .searchResult elements inserted later will be able to trigger the event handler through event propagation. Another advantage is that there is only one event handler handling the click event for all .searchResult elements, instead of having an event handler for each individual element.

Comments

0

Try

var a = $('<div  id='+value["id"]+' class="searchResult"> '+value["name"]+' </div>');
$('#append').append(a);

instead of your approach below
var a = $('<div  id='+value["id"]+' class="searchResult">  
                       '+value["name"]+' </div>').appendTo($('#append'));

Comments

0

you dont need the var a

$(stuff).appendTo(selector) is fine.

Though that is not the solution, but one observation.

So assuming your response from the back end gives a JSON like so: { id: 123, name: "name" }

Your iteration in the function $.each(data, function(k,v) {

v itself has the desired values. value["id"] is wrong and tries to access the property id of the key. So you don't need the iteration over the JSON, you can simply access its properties, if you know what they are.

Try this:

$('<div id=' + data["id"] + 'class="searchResult">' + data["name"] + ...

4 Comments

@abhi try the solution above. Don't iterate, just use data. If your JSON structure is something else, you might have to share that, so that I can provide an answer.
It'd help if we had a sample of the produced JSON. However, I believe he intends it to be an array of {key:..., value:...} pairs, so iterating makes sense.
@MattiasBuelens, I am sure. Hence I'm asking for the sample JSON. Without that, any answer, even mine would be futile :-)
@Arindam i am getting json result as [{"id":"1","name":"new_challenge1 by abhi"},{"id":"2","name":"challenge2 by abhi"}]
0

your are trying to bind the click function before the element came to dom. So do bind the event inside your loop

$(function(){      
  $("#addSearch").keyup(function() {    
    var v = $('#addSearch').val();
   $.getJSON('http://localhost/api/getresult/?q='+v, function(data){
     $('#append').html('');
      $.each(data, function (key,value){
         $('<div  id='+value["id"]+' class="searchResult">  
               '+value["name"]+' 
             </div>').appendTo($('#append'));

          bindClick();
       });
   });    
});    
});
function bindClick(){
    $('.searchResult').click(function(){
      alert($(this).attr("id"));
   });
 }

Comments

0

try like this,

$('.searchResult').live('click', function() {

alert($(this).attr("id"));

});

3 Comments

@abhi: Go through this before using live. on-vs-live-review
jQuery v.1.7 onwards the .live() method is apparently deprecated.
.live() and .delegate() have been superseded by on(). Their usage is discouraged for new code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.