I was working with some javascript code and i have a list of buttons with the same class names but i wanted to know which button among them is clicked inorder to get the value. How can I do that with vanilla js? Here is the sample code
<button onclick="chooseRating()" id="rateBtn" value="1">1</button>
<button onclick="chooseRating()" id="rateBtn" value="2">2</button>
<button onclick="chooseRating()" id="rateBtn" value="3">3</button>
<button onclick="chooseRating()" id="rateBtn" value="4">4</button>
<button onclick="chooseRating()" id="rateBtn" value="5">5</button>
and the js code i tried is
const rateBtn = document.getElementsByClassName("rateBtn");
function chooseRating() {
for (rate in rateBtn) {
console.log(rateBtn[rate]);
if (rateBtn[rate].clicked === true) {
rating = rateBtn[rate].value;
console.log(rating);
//shows 5 don't know why
}
}
}
CodePudding user response:
You should first of all define a specific id per button.
Additionally, you can pass the HTML element to your onClick method as a parameter.
So for example:
<button onclick="chooseRating(this)" id="rateBtn1" value="1">1</button>
<button onclick="chooseRating(this)" id="rateBtn2" value="2">2</button>
<button onclick="chooseRating(this)" id="rateBtn3" value="3">3</button>
<button onclick="chooseRating(this)" id="rateBtn4" value="4">4</button>
<button onclick="chooseRating(this)" id="rateBtn5" value="5">5</button>
You can then from vanilla javascript code get the ID and the value of your HTML button:
function chooseRating(e) {
console.log(`my ID is ${e.id}, and my value is ${e.value}`);
}
CodePudding user response:
let myBtns=document.querySelectorAll('.rateBtn');
myBtns.forEach(function(btn) {
btn.addEventListener('click', () => {
console.log(this.value)
});
});
CodePudding user response:
HTML :
<button onclick="chooseRating()" id="rateBtn" value="1">1</button>
<button onclick="chooseRating()" id="rateBtn" value="2">2</button>
<button onclick="chooseRating()" id="rateBtn" value="3">3</button>
<button onclick="chooseRating()" id="rateBtn" value="4">4</button>
<button onclick="chooseRating()" id="rateBtn" value="5">5</button>
Index.js :
function chooseRating(e) {
console.log (e.value);
}
you can see more in this
CodePudding user response:
You can just pass on a variable to the function-call in each button. EXAMPLE: onclick="myFunction(variable)"
HTML-file:
<button onclick="myFunction(value)" id="rateBtn" value="1">
1
</button>
<button onclick="myFunction(value)" id="rateBtn" value="2">
2
</button>
<button onclick="myFunction(value)" id="rateBtn" value="3">
3
</button>
<button onclick="myFunction(value)" id="rateBtn" value="4">
4
</button>
<button onclick="myFunction(value)" id="rateBtn" value="5">
5
</button>
JavaScript-file:
function myFunction(val) { console.log(val); }