views:

78

answers:

3

php sends html strings to html via ajax wrapped in <p class="select"></p> tags, css reads class perfectly. javascript/jquery does not. javascript/jquery wont even parse <p onclick="function()"></p>. What am i doing wrong?

heres my php (sends data via ajax fine)

echo "<p class='select' onclick='populate();' >{$row['song_name']} </p>";

heres my css (works fine)

p.select{color:#fff;padding: 5px;margin:0}
p.select:hover{color:#fff;background:#f60;cursor:pointer;}

heres my javascript method 1 jquery.

$("p .select").click(function(){
        var str = $(this).val();
        alert(str);
  });

method 2 onclick function.

function populate()
{

alert('here')
}

neither of the two methods respond at all. Guru why is this?

+1  A: 
$("p .select").live ( "click" , function(){
        var str = $(this).text();
        alert(str);
  });

See

Events/live

Binds a handler to an event (like click) for all current - and future - matched element.

rahul
Although as a P element doesn't have a value property, this still won't work: val() should probably be text(). http://docs.jquery.com/Attributes/val
NickFitz
A: 

I posted a working(in Firefox) example below. I think you forgot to put the jquery method inside the onload event. Beside the other (small) bugs...

<html>
   <head>
      <style>
         p.select{color:#fff;padding: 5px;margin:0}
         p.select:hover{color:#fff;background:#f60;cursor:pointer;}
      </style>      
      <script src="jquery-1.3.2.min(2).js" type="text/javascript"></script>
      <script type="text/javascript">         
         function bodyOnLoad() {
            //instead of "p .select" "p.select"
            $("p.select").click(
               function(){
                  //changed val() into text()
                  var str = $(this).text();
                  alert(str);
               }); 
         }
      </script>         
   </head>
   <body onload="bodyOnLoad()">
      <p class='select'>Songname</p>
   </body>
</html>
Niek H.
jQuery has a build in `$(document).ready(function(){...});` that is simpler than `<body onload="bodyOnLoad()>"`
Eric
+1  A: 

Two things:

  • p .select will choose <p> tags containing an element with class select. p.select selects <p class="select">.
  • Why not move the populate function to within the live? I suspect the jquery live (or click) removes any explicit handlers.

Try this:

$("p.select").live("click",function()
{
    var str = $(this).text();
    alert(str);
    populate();
});
Eric