Lberteh
Lberteh

Reputation: 175

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?

Upvotes: 0

Views: 1040

Answers (3)

One ID in a page should be only once. #p_name can be used only once. If you need to use that multiple time use it as a class .p_name and in your script change it:

<h3 class="p_name" data-proname="<?php echo $project->project_name ?>"><?php echo $project->project_name ?></h3>

Upvotes: 1

user94559
user94559

Reputation: 60143

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

Upvotes: 1

user5286777
user5286777

Reputation:

You should use $(this) to get the clicked element.

$("h3").click(function() {
    var pName = $(this).data("proname");
    alert(pName);
});

And, if you're hooking the click event to a parent of the h3, you can use $(this).find("h3") to grab it.

Upvotes: 1

Related Questions