"reuse" a JavaScript code for multiple buttons

169 views Asked by At

I am fairly new to JavaScript, I have ben working on a simple if else script to change the color of at button, depending on the status of a variable that I get from a plc (Siemens S7-1200).

The script is working fine and the color of the button is changing. But I have 10 buttons that I want to run this script on.

Is it possible to “reuse” the script so that I don’t have to copy the script and change the variables for every button

T

<script>
var tag = ':="web_DB".outtag1:'
var button = "button1"
window.onload = function() {
if (tag == 1) {
    document.getElementById(button).style.backgroundColor = 'green';
} else{
    document.getElementById(button).style.backgroundColor = 'red';
}

}
    </script>

    <form>
<input type="submit" id="button1" value="button">
<input type="hidden" name='"web_DB".intag1' value ="1">
</form>
1

There are 1 answers

3
Rocky Sims On

It's hard to be sure since you haven't posted all your code and what you have posted doesn't actually work but I think you're looking for something like this.

const tags = [
    ':="web_DB".outtag1:',
    ':="web_DB".outtag2:',
    //...
    ':="web_DB".outtag10:'
];
window.onload = function() {
    for (let i = 0; i <= 9; i++) {
        const color = (tags[i] == 1) ? 'green' : 'red';
        document.getElementById('button' + (i+1)).style.backgroundColor = color;
    }
}