tags:

views:

134

answers:

2

<li> is kept by the set_input() function, After getting data by using a getJSON(). But even bind function is not working. could anybody pls help me!

$(document).ready(function()
{

$.getJSON("sample1.php?",
    function(data){
    $.each(data, function(i,j){
    testA[j.id]=j.name;
   });
   set_input("div_1","continent",testA);
 });

$("#"+div_D+" ul li").bind("click",function(){
 $("#"+div_D+" input[type='text']").val($(this).text());
}) 
});


  function set_input(div_D,name_N,Array_A){

 $("#"+div_D).html("<input id="+name_N+">");
 var str="<ul>";
 $.each(Array_A,function(m,n){
  str +="<li>"+n+"</li>"
 })
 $("#"+div_D+" input[type="text"]").after(str);
  }


  This is JSON array:
[ {'id':'0','name':'Africa'},{'id':'1','name':'Americas'},{'id':'2','name':'Asia'},{'id':'3','name':'Europe'},{'id':'4','name':'Oceania'} ]
+2  A: 

You are trying to bind to an item which does not exist in the DOM yet.

Move

$("#"+div_+" ul li").bind("click",function(){
        $("#"+div_+" input[type="text"]").val($(this).text());
})

to the last line of the set-input function. i.e. to

function set-input(div_,name_,Array_){
        $("#"+div_).html("<input id="+name_+">");
        var str="<ul>";
        $.each(Array_,function(m,n){
                str +="<li>"+n+"</li>"
        })
        $("#"+div_+" input[type="text"]").after(str);

    $("#"+div_+" ul li").bind("click",function(){
     $("#"+div_+" input[type="text"]").val($(this).text());
    })
}

P.S. You have quite a few typos.

Cherian
Is there any other possible way?I don't want to keep that code to the last line of the set-input function
Srikanth
Because that set-input function is in another file, I want to write click function in another file!
Srikanth
Add ur code in a custom event that attaches to set-input() and then trigger that event :-)
Cherian
Event driven programming :-)
Cherian
Additionally you could use $().live()
Cherian
A: 

I see several errors:

  • testA is never declared, and will be assumed global
  • set-input isn't a valid function name
  • " input[type="text"]" should be " input[type='text']"
  • str should be equal to $("ul") (maybe, not entirely sure what you're trying for)
  • you are creating multiple inputs which will all have the same id, use class instead

It would help if you posted the HTML you are running this against

Also as a rule of thumb for writing clean jQuery code, I try to almost never use concatenation inside a $(), there is almost always a better way.

cobbal