1

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?

3 Answers 3

1
$("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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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();
});

Comments

0

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>

1 Comment

jQuery has a build in $(document).ready(function(){...}); that is simpler than <body onload="bodyOnLoad()>"

Your Answer

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