Question

I shortened my code dramatically but below relays the point pretty efficiently, I'm trying to get the variable "Monitor" to update if the buttons pressed. I can get the variable through to my code if I put all of my code inside of the "button.onclick" function. However, my code won't run until I press the button. I need my code to run and if a button is pressed it updates my code.

<form name="form1">
  <span id="buttons">
    <input type="button" name="button1" value="funny1"/>
    <input type="button" name="button2" value="funny2"/>
  </span>
</form>
<script type="text/javascript">
    var Monitor, buttonsDiv=document.getElementById("buttons");
    Monitor = "funny1"
    for (var i=1; i<=2; i++) {
        var button = document.form1["button" + i];
        button.onclick = function() {
            buttons.Monitor = this.value;
        };

        /*lots of my own code that runs
        inside of my for loop waiting
        to reference monitor for an update*/

</script>
Was it helpful?

Solution

Hopefully the following code will get you going in the right direction. Instead of wiring up all the events per button, I think you were trying to get it so each button would then call into a function that would set the value of Monitor.

var Monitor = "funny1";

//selecting all elements named button  
var buttons = document.querySelectorAll('input[type="button"]');

//For each of the buttons wire up an event listener
for(var i=0, length=buttons.length; i < length;i++)
{
    //create a reference shorthand
    var button = buttons[i];

    //add the event listener for a click
    button.addEventListener('click', function(event)
    {
        //on the event look at the event's target property to find the element that invoked the click
        Monitor = event.target.value;
        console.log(Monitor);  //Output the value of monitor the the console
    });    
}

This code first finds all the inputs with type=button. I suggest you perhaps give the inputs a class instead to make the selector clearer, your choice. Secondly, I loop through the buttons and wire an event up for each one. The event then sets the value of the Monitor variable.

http://jsfiddle.net/wcf4c/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top