MV-123 MV-123 - 1 year ago 83
HTML Question

Populate field depending on which button in a loop has been clicked

I have a custom loop using Advanced Custom Fields which displays three boxes each with content.

If the button in box 1 has been selected, I want the content in box 1 to populate into the input.

If the button in box 2 has been selected, I want the content in box 2 to populate into the input and so on.

My html is below:

<div class="row">
<?php if( have_rows('event') ): while ( have_rows('event') ) : the_row(); ?>
<div class="four">
<div class="input"><?php the_sub_field('details'); ?></div>
<a class="button btn" href="#contact">Make an appointment</a>
<?php endwhile; else : endif; ?>

<input id="output"></input>

And my jQuery is:

jQuery(document).ready(function($) {
$(".btn").click(function(e) {

I have managed to find working solutions for one box but not for a loop, I suspect it might be something do with .each() but I am not sure.


Answer Source

Your jQuery is very close.

There are two issues:

  1. You are attempting to use the .val() of a div, which doesn't have a value - it has text, so you need to use .text()
  2. You are putting the value if the first .input element into the input, when you want the .input that is related to the button clicked. There's a couple of ways to do this, but in your case, the most direct would be to use .siblings.

    // Short-hand document ready (which is no-conflict safe, necessary in WP scripts)  
    jQuery(function($) {
        $(".btn").click(function(e) {
            // $(this) is this button - get the sibling .input element's text
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download