I have this code:
<script type="text/javascript">
function changestate()
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(document.getElementById("Play").onclick == true)
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick="changestate();"/>
I’m trying to know when the button is clicked, and have that if button is clicked in the if statement. I want to know this so I can change the value that is inside the text box. The problem is, I do not know how to tell when the button is clicked. If you could help me out that would be great.
The
onclickattribute identifies what should happen when the user clicks this particular element. In your case, you’re asking that a function be ran; when the function runs, you can rest assured that the button was clicked – that is after all how the function itself got put into motion (unless you invoked it some other way).Your code is a bit confusing, but suppose you had two buttons and you wanted to know which one was clicked, informing the user via the
stateTextBoxvalue:You can test this code live at http://jsfiddle.net/Y53LA/.
Note how we add event-listeners on our
playButtonandignoreButton. This permits us to keep our HTML clean (no need for anonclickattribute). Both of these will fire off thechangeStatefunction anytime the user clicks on them.Within the
changeStatefunction we have access to aneventobject. This gives us some details about the particular event that took place (in this case, theclickevent). Part of this object is thetarget, which is the element that was clicked. We can grab theidproperty from that element, and place it into thevalueof thestateTextBox.Here is the adjusted HTML: