heinst heinst - 1 year ago 150
HTML Question

How to tell if a button is clicked

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";
<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.

Answer Source

The onclick attribute 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 stateTextBox value:

(function () {
    // Enables stricter rules for JavaScript
    "use strict";
    // Reference two buttons, and a textbox
    var playButton = document.getElementById("play"),
        stateTextBox = document.getElementById("state"),
        ignoreButton = document.getElementById("ignore");
    // Function that changes the value of our stateTextBox
    function changeState(event) {
        stateTextBox.value = event.target.id + " was clicked";
    // Event handlers for when we click on a button
    playButton.addEventListener("click", changeState, false);
    ignoreButton.addEventListener("click", changeState, false);

You can test this code live at http://jsfiddle.net/Y53LA/.

Note how we add event-listeners on our playButton and ignoreButton. This permits us to keep our HTML clean (no need for an onclick attribute). Both of these will fire off the changeState function anytime the user clicks on them.

Within the changeState function we have access to an event object. This gives us some details about the particular event that took place (in this case, the click event). Part of this object is the target, which is the element that was clicked. We can grab the id property from that element, and place it into the value of the stateTextBox.

Here is the adjusted HTML:

<input type="button" value="Play with Pogo" id="play" />
<input type="text" id="state" />
<input type="button" value="Ignore with Pogo" id="ignore" />‚Äč
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download