0

I have the following problem: I have some buttons named stripe_pro_new, stripe_pro_new2, stripe_pro_new3 etc. And I have 2 functions that return 2 attributes. How can I return the attribute of the button that I press? (current function return the attributes for "stripe_pro_new")

button example:

<button 
  id="stripe_pro_new" 
  name="pro_plan" 
  data-name="<?php echo __( 'Month' );?>" 
  data-price="<?php echo (float)$config->basic_pro_plan;?>" 
  class="btn stripe valign-wrapper">
    <?php echo __( 'buy_now' );?> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M20,8H4V6H20M20,18H4V12H20M20,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V6C22,4.89 21.1,4 20,4Z"></path>
    </svg>
</button>

functions that return the attribute stripe_pro_new:

function getDescription() {
    var val = document.getElementById("stripe_pro_new").getAttribute("data-name");  
    return val;
}

function getPrice() {
    var val1 = document.getElementById("stripe_pro_new").getAttribute("data-price");  
    return val1;
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • @HereticMonkey yes. but how to parse that info to getDescription and getPrice? because i call it later ``` function reply_click(clicked_object) { alert(clicked_object.getAttribute('data-name')); alert(clicked_object.getAttribute('data-price')); } function getDescription() { var val = document.getElementById("stripe_pro_new").getAttribute("data-name"); return val; } function getPrice() { var val1 = document.getElementById("stripe_pro_new").getAttribute("data-price"); return val1; }``` – Eduard Krusher Feb 21 '22 at 14:56
  • Ask a new question if you have a different question. Say ahead of time what you need the attribute values for and where how you will be using them. Currently, you've shown nothing calling `getDescription` or `getPrice`. Storing the information after clicking the button for later retrieval is a different question that getting the information from the clicked button. – Heretic Monkey Feb 21 '22 at 23:25

1 Answers1

-1

html

<button data-name="btn-1" data-price="price1">Button</button>
<button data-name="btn-2" data-price="price2">Button</button>
<button data-name="btn-3" data-price="price3">Button</button>

js

var buttons = document.querySelectorAll("button");

buttons.forEach(function (item, index) {
  item.addEventListener('click', function(){    
    var description = getDescription(this);
    var price = getPrice(this);
  });
});

function getDescription(clicked_element) {
    var val = clicked_element.getAttribute("data-name");  
    return val;
}

function getPrice(clicked_element) {
    var val = clicked_element.getAttribute("data-price");  
    return val;
}

Alex
  • 76
  • 7