最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript function on multiple buttons - Stack Overflow

programmeradmin1浏览0评论

I have three buttons. I would like them to change colour when pressed, and back to no colour when pressed again.

I found this code on stackoverflow that allows me to almost do it however, it only works on one button, the other two are not affected.
Also, when I pressed one of the other two buttons, the first button changes colour. I tried changing ID's on the buttons, adding another script with different getElementById() ID's but nothing works.

Do I need more than one function to achieve what I want?

The code I am using is below.

var count = 1;
function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "#FFFFFF";
    count = 1;
  } else {
    property.style.backgroundColor = "#E68352";
    count = 0;
  }
}
<head>
  <link rel="stylesheet" type="text/css" href="styles/main.css"/>
</head>
<body>
  <input type="button" id="button" value = "A-D" style= "color:black" onclick="setColor('button', '#101010')";/>
  <input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
  <input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
</body>

I have three buttons. I would like them to change colour when pressed, and back to no colour when pressed again.

I found this code on stackoverflow that allows me to almost do it however, it only works on one button, the other two are not affected.
Also, when I pressed one of the other two buttons, the first button changes colour. I tried changing ID's on the buttons, adding another script with different getElementById() ID's but nothing works.

Do I need more than one function to achieve what I want?

The code I am using is below.

var count = 1;
function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "#FFFFFF";
    count = 1;
  } else {
    property.style.backgroundColor = "#E68352";
    count = 0;
  }
}
<head>
  <link rel="stylesheet" type="text/css" href="styles/main.css"/>
</head>
<body>
  <input type="button" id="button" value = "A-D" style= "color:black" onclick="setColor('button', '#101010')";/>
  <input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
  <input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
</body>

Share Improve this question edited Feb 16, 2017 at 15:32 user7393973 2,4504 gold badges28 silver badges70 bronze badges asked Feb 16, 2017 at 14:42 RobertoRoberto 391 gold badge1 silver badge6 bronze badges 5
  • IDs should be unique! – ibrahim mahrir Commented Feb 16, 2017 at 14:44
  • SO I should have three different functions and three buttons with different IDs? – Roberto Commented Feb 16, 2017 at 14:46
  • No. Pass (this) and you have access to the clicked button regardless of ID or class – mplungjan Commented Feb 16, 2017 at 14:46
  • No, just one function but call it with different IDs! – ibrahim mahrir Commented Feb 16, 2017 at 14:47
  • Not exactly duplicate as OP is using style instead of class. stackoverflow./questions/14615712/… – Rajesh Commented Feb 16, 2017 at 14:59
Add a ment  | 

8 Answers 8

Reset to default 2

Usually, when you write inline event handler you may take advantage of:

  • this: current element: When code is called from an in–line on-event handler, its this is set to the DOM element on which the listener is placed:
  • event: event element object

Therefore, change:

onclick="setColor('button', '#101010')"

with:

onclick="setColor(this, event, '#101010')"

So your code can be rewritten as:

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? 'rgb(' +
        parseInt(result[1], 16) + ', ' +
        parseInt(result[2], 16) + ', ' +
        parseInt(result[3], 16) + ')'
     : null;
}


function setColor(btnEle, evt, color) {
    if (btnEle.style.backgroundColor == hexToRgb("#E68352")) {
        btnEle.style.backgroundColor = "#FFFFFF"
    }
    else {
        btnEle.style.backgroundColor = "#E68352"
    }
}
<input type="button" id="button1" value = "A-D" style= "color:black" onclick="setColor(this, event, '#101010')";/>
<input type="button" id="button2" value = "E-H" style= "color:black" onclick="setColor(this, event, '#101010')";/>
<input type="button" id="button3" value = "E-H" style= "color:black" onclick="setColor(this, event, '#101010')";/>

You should have uniques ID

You can use classList.toggle("yourClass") instead of using a count

var buttons = document.getElementsByClassName("button");
for (let i = 0, l = buttons.length; i < l; i++) {
  buttons[i].addEventListener('click', function() {
    buttons[i].classList.toggle('active');
  })
}
.active {
  background-color: #E68352 !important;
}

.button {
  background-color: #FFFFFF;
}
<input type="button" id="button1" class="button" value="A-D" />
<input type="button" id="button2" class="button" value="E-H" />
<input type="button" id="button3" class="button" value="E-H" />

Set a class on the buttons, and then loop through the buttons and add an event listener to each of them:

EDIT: I see you are using an onclick handler, which I didn't notice at first; so this answer might not be as useful as I thought. You should definitely use different IDs though if you use that approach.

<button class="button" ... >

var buttons = document.getElementsByClassName('button')
for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', function() {
        // Do your button things.
    })
}   

IDs should be unique inside the document. Like this:

<input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#101010')" ;/>
<--                       here ^                                                      here ^               -->
<input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#101010')" ;/>
<--                       here ^                                                      here ^               -->
<input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#101010')" ;/>
<--                       here ^                                                      here ^               -->

<!DOCTYPE html>
<html>

<head>
  <script>
    var count = 1;

    function setColor(btn, color) {
      var property = document.getElementById(btn);
      if (count == 0) {
        property.style.backgroundColor = "#FFFFFF"
        count = 1;
      } else {
        property.style.backgroundColor = "#E68352"
        count = 0;
      }
    }
  </script>

  <link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>

<body>

  <input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#101010')" ;/>
  <input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#101010')" ;/>
  <input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#101010')" ;/>

</body>

</html>

IDs need to be unique but you do not need them here

Give the buttons a class and use toggle the classList

window.onload=function() {
  var buts = document.querySelectorAll(".but");
  for (var i=0;i<buts.length;i++) {
    buts[i].onclick=function() {
      this.classList.toggle("clicked");
    }
  }
}
.but {background-color:black}
.clicked { background-color:#E68352; }
<input type="button" value="A-D" class="but" />
<input type="button" value="E-F" class="but" />
<input type="button" value="G-H" class="but" />

dont use numbers, use this instead http://codepen.io/animhotep/pen/qRwjeX?editors=0010

var count = 1;

function setColor(btn, color) {
  if (count == 0) {
    btn.style.backgroundColor = "#FFFFFF"
    count = 1;
  }
  else {
    btn.style.backgroundColor = "#E68352"
    count = 0;
  }
}

Roberto, as Ibrahim correctly pointed out, the problem is that you are using the same ID for all buttons. When javascript executes this code:

var property = document.getElementById(btw);

it will always return the first element with the ID specified. One solution is choosing a different ID for each button and updating the corresponding onclick code. Another solution could be the one below, in which you do not need to specify IDs at all and the function setColor could be used for any element.

<!DOCTYPE html>
<html>
<head>
<script>
var count = 1;
function setColor(element, color) {
    if (count == 0) {
        el.style.backgroundColor = "#FFFFFF"
        count = 1;
    }
    else {
        el.style.backgroundColor = "#E68352"
        count = 0;
    }
}
</script>
<link rel="stylesheet" type="text/css" href="styles/main.css"/>
</head>

<body>
    <input type="button" value = "A-D" style= "color:black" onclick="setColor(this, '#101010')";/>
    <input type="button" value = "E-H" style= "color:black" onclick="setColor(this, '#101010')";/>
    <input type="button" value = "E-H" style= "color:black" onclick="setColor(this, '#101010')";/>
</body>
</html>

Note the use of the this variable as the first argument for setColor. In each of the buttons, the corresponding this will point to the element where it is defined.

Hope it helps.

You just need little bit of modification. See the working code.

function setColor(btn, color) {
  var elem = document.getElementById(btn);

  if (elem.hasAttribute("style")) {
    if (elem.getAttribute("style").indexOf("background-color:") == -1) {
          elem.style.backgroundColor = color;
    } else {
          elem.style.backgroundColor = "";
    }
  }
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>

<body>

  <input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#E68352')" ;/>
  <input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#E68352')" ;/>
  <input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#E68352')" ;/>

</body>

</html>

发布评论

评论列表(0)

  1. 暂无评论