简体   繁体   中英

button checking a checkbox using javascript

I am trying to make a button that will toggle between three colors: black, green, and red and will either check a certain box depending on the color. Right now I can make the color toggle but I can't make the check boxes check. I would appreciate the help. I am a beginner (obviously).

Button color green: check box 1

Button color red: check box 2

Button color black: do not check either box 1 or 2

The script looks like:

<script>
var colors = ["green", "red", "black"] 

function setColor(el) { 
el.colorIdx = el.colorIdx || 0; 
el.style.color = colors[el.colorIdx++ % colors.length]; 
}

</script>

The HTML looks like:

<html>
<button onclick="setColor(this)">This is my Button</button>
<input type="checkbox" name="box1" id="box1" />
<input type="checkbox" name="box2" id="box2" />  
</html>

Thanks!

I'd suggest:

var colors = ["green", "red", "black"];

function setColor(el) {
    el.colorIdx = el.colorIdx || 0;
    el.style.color = colors[el.colorIdx++ % colors.length];
    document.getElementById('box1').checked = el.style.color == 'green';
    document.getElementById('box2').checked = el.style.color == 'red';
}

JS Fiddle demo .

Do it like this:

var index = el.colorIdx++ % colors.length;
if( index == 2 ) //2 is the index of color black
{
  document.getElementById("box1").checked = false; 
  document.getElementById("box2").checked = false; 
}
else if( index == 0 )
{
   document.getElementById("box1").checked = true;     
}
else
{
   document.getElementById("box2").checked = true;       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM