0

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?

1
  • you should not user id in loop because ID have to be unique through the page. Commented Jul 21, 2016 at 4:36

3 Answers 3

1

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'));
});
Sign up to request clarification or add additional context in comments.

1 Comment

You're correct, I messed up using id instead of a class. But even using a class it didn't work using: pName = $('.p_name').data('proname'); alert(pName); Using alert($(this).find('h3').data('proname')); it did work. Thanks a lot.
1

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.

Comments

1

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>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.