Get unique id after the fact?
Question by qitch
I want to be able to change a button image on click which isn’t the issue. Each button is unique to information that is pulled from the database and on click the button should change and send the appropriate info to the database. What I am unsure about is how I can change the specific button. Say there are five things up, so five buttons. Each button has its unique id to go with its information. How can I find out what the id is so that I can manipulate the button?
I use php to grab the info from the database and go through a while loop to get it all displayed. Once it is all displayed it is there for the user to see and then they can click on the button.
edit – It just came to me. I can make my onclick function take a variable and feed the variable into it. Right?
Answer by Starx
A simple trick actually. Call a function on the click and pass its id, to it as a parameter.
<button id="id1" onClick="handleclick(this.id)">Button1</button>
<button id="id2" onClick="handleclick(this.id)">Button2</button>
<script>
function handleclick(id)
{
alert(id); //here is your id
}
</script>
Demo
Alternative
You can do something like this also
buttons = document.getElementsByTagName("button");
for( var x=0; x < buttons.length; x++ ) {
buttons[x].onclick = handleclick;
}