Wilx
Wilx

Reputation: 53

How to check some button value with same id javascript

well guys , i'm new in here ... how can i check the values on different button with the same id?

sample code:

<button onclick="checkValue();" id="price" value="1">
<button onclick="checkValue();" id="price" value="2">
<button onclick="checkValue();" id="price" value="3">
<script>
function checkValue()
    {
        var but = document.getElementById("price").value;
        console.log(but);
    }
</script>

well .. how can i obtain 1 or 2 or 3 when it was clicked?

Upvotes: 0

Views: 2380

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115222

The id should be unique so always use class for the group of elements. For getting the value pass the this context as the argument.

<button onclick="checkValue(this);" value="1">1</button>
<button onclick="checkValue(this);" value="2">2</button>
<button onclick="checkValue(this);" value="3">3</button>
<script>
  function checkValue(ele) {
    console.log(ele.value);
  }
</script>

Upvotes: 3

ozil
ozil

Reputation: 7117

<button onclick="checkValue(this);" class="price" id="price1" value="1">Button1
<button onclick="checkValue(this);" class="price" id="price2" value="2">Button2
<button onclick="checkValue(this);" class="price" id="price3" value="3">Button3
<script>
function checkValue(d)
    {
        var but = d.value;
        console.log(but);
    }
</script>

Upvotes: 0

Weedoze
Weedoze

Reputation: 13943

You should not have multiple elements with the same id. If you want to group them you can use class.

To get the value of the selected button you can send this inside the function

function checkValue(elem) {
  console.log(elem.value);
}
<button onclick="checkValue(this)" class="price" value="1">1</button>
<button onclick="checkValue(this)" class="price" value="2">2</button>
<button onclick="checkValue(this)" class="price" value="3">3</button>

Upvotes: 0

Related Questions