MV-123 MV-123 - 1 month ago 8
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>
</div>
<?php endwhile; else : endif; ?>
</div>

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


And my jQuery is:

jQuery(document).ready(function($) {
$(".btn").click(function(e) {
$("#output").val($(".input").val());
});
});


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.

Thanks.

Answer

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
            $("#output").val($(this).siblings(".input").text());    
        });
    });