Lberteh Lberteh - 4 months ago 12
PHP Question

jquery - get html of element after foreach loop

Not sure how to do this. I get a list of projects using php and mysql.

I display the project using a loop. Then using jquery click() I wanna grab the html of the element where I displayed the project name to use the name somewhere else, but it doesn't matter what project I click, I always get only the first project of the loop.

here is the code:

<?php foreach ($projects as $project): ?>
<li class="todo-projects-item" data-projectid="<?php echo $project->project_id ?>">
<h3 id="p_name" data-proname="<?php echo $project->project_name ?>"><?php echo $project->project_name ?></h3>
<p><?php echo $project->project_body ?></p>
<div class="todo-project-item-foot">
<p class="todo-red todo-inline">Project #<?php echo $project->project_id ?></p>
<p class="todo-inline todo-float-r">32 Members
<a class="todo-add-button" href="#todo-members-modal" data-toggle="modal">+</a>
</p>
</div>
</li>
<div class="todo-projects-divider"></div>
<?php endforeach; ?>


It gives me the following:

list

I'm using this in my script with the click function:

pName = $('#p_name').data('proname');
alert(pName);


It doesn't matter what project I click, it always alerts "The Project", the first within my array... what am I doing wrong?

Answer

What element is the click handler on?

The issue is that you're using $('#p_name'), but you actually have many elements on the page with that same ID. This is actually a big no-no... element IDs should always be unique.

If the click handler is on the <li> tag, something like this should work better:

$('.todo-projects-item').click(function (e) {
    e.preventDefault();
    alert($(this).find('h3').data('proname'));
});
Comments