skip to Main Content

help me get the value from the button, I can not

my code:

   <a href="" onclick="funk(this)" value="123" class="price-button"><i class="fas fa-shopping-cart"></i> press</a>
    <script>
     funk = (a) => {
    console.log(a.value)
    
    }
    </script>

2

Answers


  1. Set a value in HTML and retrieve it on click with getAttribute

    <a href="" value="123" class="price-button" onclick="funk(this)"><i class="fas fa-shopping-cart"></i> press</a>
    
    const funk = (a) => {
        console.log(a.getAttribute("value"))
    }
    
    Login or Signup to reply.
  2. There’s a few issues in your code:

    • The link will transfer the page, so you probably need to preventDefault
    • a elements don’t have a value attribute. Use a data attribute to add custom metadata to an element
    • Use an unobtrusive event binding, not outdated onclick attributes

    Here’s a corrected version using plain JS:

    document.querySelectorAll('.price-button').forEach(el => {
      el.addEventListener('click', e => {
        e.preventDefault(); // stop the page transfer
        const button = e.target;
        console.log(button.dataset.value);
      });
    });
    <a href="#" data-value="123" class="price-button">
      <i class="fas fa-shopping-cart"></i> 
      press
    </a><br />
    <a href="#" data-value="456" class="price-button">
      <i class="fas fa-shopping-cart"></i> 
      press
    </a>

    And the same thing in jQuery, as you tagged that as well:

    jQuery($ => {
      $('.price-button').on('click', e => {
        e.preventDefault(); // stop the page transfer
        const $button = $(e.target);
        console.log($button.data('value'));
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <a href="#" data-value="123" class="price-button">
      <i class="fas fa-shopping-cart"></i> 
      press
    </a><br />
    <a href="#" data-value="456" class="price-button">
      <i class="fas fa-shopping-cart"></i> 
      press
    </a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search