简体   繁体   中英

JavaScript function in twig foreach

I have this code that has the phone number of different posters.

{% for ad in ads %}
...
    <a class="btn"  onclick="showNumber()" id="showNumber"><span class="fa fa-phone"></span> View Phone Number</a>

    <input id="phonenum" style="display: none;" type="text" value="{{ ad.user.phone }}">
...
{% endfor %}

and the Javascript function

<script type="text/javascript">
  function showNumber() {
  document.getElementById('showNumber').innerHTML = document.getElementById('phonenum').value;
}
</script>

the above works and the input field shows correctly the different numbers of the posters when i change it to block. But the problem is that the phone number of the first button on the first button shows regardless of which button i click. what else should i do there?

IDs are meant to be unique, you're creating elements in a loop and giving them the same ID ( phonenum ), instead of IDs you should use class names and retrieve the appropriate element base on which anchor was clicked. Here is an example:

{% for ad in ads %}
...
    <a class="btn" onclick="showNumber(e)"><span class="fa fa-phone"></span> View Phone Number</a>

    <input class="phonenum" style="display: none;" type="text" value="{{ ad.user.phone }}">
...
{% endfor %}

<script type="text/javascript">
  function showNumber(e) {
    e.target.innerHTML = e.target.parent.querySelector('.phonenum').value;
  }
</script>

In this example, e.target is the clicked anchor and I'm using e.target.parent.querySelector('.phonenum') to retrieve the input associated with the anchor (I'm assuming they have the same parent element).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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