Home > Mobile >  pick up a value from the button
pick up a value from the button

Time:01-13

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

my code:

   <a href="" onclick="funk(this)" value="123" ><i ></i> press</a>
    <script>
     funk = (a) => {
    console.log(a.value)
    
    }
    </script>

CodePudding user response:

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

<a href="" value="123"  onclick="funk(this)"><i ></i> press</a>
const funk = (a) => {
    console.log(a.getAttribute("value"))
}

CodePudding user response:

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" >
  <i ></i> 
  press
</a><br />
<a href="#" data-value="456" >
  <i ></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" >
  <i ></i> 
  press
</a><br />
<a href="#" data-value="456" >
  <i ></i> 
  press
</a>

  • Related