Ave
Ave

Reputation: 4430

How to passing value of <input> into href of <a> tag?

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>

Upvotes: 1

Views: 250

Answers (2)

Ngoan Tran
Ngoan Tran

Reputation: 1527

I suggest you to use id to identify a tag instead of class.

Then use document.getElementById() to get this tag and assign value to 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>

Upvotes: 1

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

Use attr API:

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

or

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

Upvotes: 1

Related Questions