简体   繁体   English

根据单击循环中的哪个按钮来填充字段

[英]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. 如果已选择框1中的按钮,我希望框1中的内容填充到输入中。

If the button in box 2 has been selected, I want the content in box 2 to populate into the input and so on. 如果已选择框2中的按钮,则希望框2中的内容填充到输入中,依此类推。

My html is below: 我的HTML如下:

<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是:

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. 我设法找到了一个盒子的有效解决方案,但没有找到一个循环,我怀疑这可能与.each()有关,但我不确定。

Thanks. 谢谢。

Your jQuery is very close. 您的jQuery非常接近。

There are two issues: 有两个问题:

  1. You are attempting to use the .val() of a div , which doesn't have a value - it has text (or html), so you need to use .text() (or .html() ). 您尝试使用的div.val()没有value -它具有text (或html),因此您需要使用.text() (或.html() )。 In your case, I believe .text is what you are after. 就您而言,我相信.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. 当您想要与按钮相关的.input ,将第一个 .input元素的值放入输入中。 There's a couple of ways to do this, but in your case, the most direct would be to use .siblings . 有两种方法可以执行此操作,但是对于您而言,最直接的方法是使用.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()); }); }); 

You just need to get the sibling input of the clicked button. 您只需要获取单击按钮的同级输入即可。 However, you do need to make your div class="input" an actual input for .val() to work. 但是,您确实需要使div class="input"成为.val()的实际input才能起作用。 Otherwise, you will have to use .text() to get the text in the div. 否则,您将必须使用.text()来获取div中的文本。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM