Skip to content

data-id always returns the same value

I am calling an api using ajax which returns me a list of available coaches in a particular area. I am then displaying each coach and his details(firstname, picture, email etc) in a div using foreach loop. Each div has a contact button which should send an email to the coach so in order to get the coach email, I have put a hidden span element in each coach details and assigned it the value of coach email. Now, when I try to get the value of that span, I always get the value of first coach in the list. My HTML code for displaying the coaches:

<!-- Single Coach Item -->
    <li class="product">
        <div class="post_item_wrap">
            <div class="post_featured">
                <div class="post_thumb">
                    <a href="#">
                        <img src="<?php echo './api/' . $coach["profile_picture"]; ?>" id="coach_image" alt="image" class="coach_img" />
                    </a>
                </div>
            </div>
            <div class="post_content">
                <!-- Hidden field below -->
                <span data-id="<?php echo $coach["email_address"]; ?>" class="hidden_fields coach_email"></span>


                <!-- Name and Bio -->
                <h3 class="coach_name"><?php echo $coach["first_name"] . " " . $coach["last_name"]; ?></h3>
                <span class="price description">
                    <span class="description"><?php echo $coach["coach_bio"]; ?></span>
                </span>
            </div>
        </div>
    </li>

Button which triggers the click event:

<span class="sc_button sc_button_square sc_button_style_2 sc_button_size_small contact_btn">
    <span class="cube flip-to-top">
        <span class="default-state sc_button_iconed none">
            <span>Contact Me</span>
        </span>
        <span class="active-state sc_button_iconed none">
            <span>Contact Me</span>
        </span>
    </span>
</span>

And this is how I am trying to get the coach email on button click:

$(".contact_btn").click(function(e){
    var coach_email=$(".coach_email").data("id");  
    console.log(coach_email);
});

Answer

If the button has a common parent with your hidden field you can use closest to get this common parent and find to go down to your hidden field. For example if your button and your hidden field are in the same div with the class “product_div’ :

$(".contact_btn").click(function(e){
    var coach_email=$(this).closest('.product_div').find('.coach_email').attr('data-id');  
    console.log(coach_email);
});