Home > Enterprise >  How to get value of the button pressed by using onclick in html. I have 6 buttons with same class na
How to get value of the button pressed by using onclick in html. I have 6 buttons with same class na

Time:10-16

I want to get value of the button pressed. i have 6 buttons as folllows:

<button  value="100" onclick="buytheme()">Points:100</button>
<button  value="200" onclick="buytheme()">Points:200</button>
<button  value="300" onclick="buytheme()">Points:300</button>
<button  value="400" onclick="buytheme()">Points:400</button>
<button  value="500" onclick="buytheme()">Points:500</button>
<button  value="600" onclick="buytheme()">Points:600</button>

following is my js function:

 function buytheme(){
    document.getElementsByClassName("theme");
}

i have also tried:

const pbtn=document.querySelectorAll("button.theme");
for(var i=0;i<pbtn.length;i  ){
(pbtn[i].onclick)=()=>{
    console.log(pbtn[0].value);
}
}

but none of following seems to work. please help me how to get exact value of the button i press.

CodePudding user response:

You can look over all of the elements with the class name theme and add a addEventListener to all of them, and log it's value.

<button  value="100">Points:100</button>
<button  value="200">Points:200</button>
<button  value="300">Points:300</button>
<button  value="400">Points:400</button>
<button  value="500">Points:500</button>
<button  value="600">Points:600</button>

<script lang="js">
    const buttons = document.getElementsByClassName("theme");
    for (let i = 0; i < buttons.length; i  ) {
        buttons[i].addEventListener("click", function() {
            const value = this.value;
            console.log(value);
        });
    }
</script>

CodePudding user response:

You can make use of eventlisteners and e.target.value to resolve this,

<button  value="100" >Points:100</button>
<button  value="200" >Points:200</button>
<button  value="300" >Points:300</button>
<button  value="400" >Points:400</button>
<button  value="500" >Points:500</button>
<button  value="600" >Points:600</button>
<script lang="js">
document.querySelectorAll('.theme').forEach(button=>{
    button.addEventListener('click',(event)=>{
        console.log(event.target.value);
    })
})
</script>
  • Related