如何将<input />的值传递给<a> tag?

时间:2017-02-21 07:37:55

标签: javascript jquery html

I have a <input> with type hidden to get value from a loop.

I want to pass values of <input> into attribute href of <a> tag.

My code:

<section id="block-text">
    <a class='moreInfo' target='_blank' href=""><button class='btnMoreInfo'>MORE INFO</button></a>
</section>

<section id="block-product">
    <input class="link_product_input" type="hidden" value="<?php echo $item->link_product; ?>">
</section>

<script>
  window.addEventListener('load', function () {
    document.getElementsByClassName("moreInfo").href = $('.link_product_input').val();
  }, false);
</script>

2 个答案:

答案 0 :(得分:1)

使用attr API:

$(".moreInfo").attr('href', $('.link_product_input').val() );

document.getElementsByClassName("moreInfo")[0].href = $('.link_product_input').val()

答案 1 :(得分:1)

我建议您使用id来标识a代码,而不是class

然后使用document.getElementById()获取此标记并将值分配给href

<section id="block-text">
    <a id="link-button" class='moreInfo' target='_blank' href=""><button class='btnMoreInfo'>MORE INFO</button></a>
</section>

<section id="block-product">
    <input class="link_product_input" type="hidden" value="<?php echo $item->link_product; ?>">
</section>

<script>
  window.addEventListener('load', function () {
    document.getElementById("link-button").href = $('.link_product_input').val(); 
  }, false);
</script>