jebmarcus jebmarcus - 4 months ago 16
CSS Question

How to change border color of checkboxes in Javascript

I am learning how to do form validation on various types of elements and want to do this in only Javascript. I have some checkboxes here and a Javascript function that checks if the checkboxes has at least one option selected on form submission. Basically the checkboxes should show up red if no option is selected. But I get the error:


Uncaught TypeError: Cannot set property 'borderColor' of undefined




function validate() {
var ok = true;
var yes = document.getElementById("yes").checked
var no = document.getElementById("no").checked;

if (!yes && !no) {
document.getElementsByClassName(".btn-group").style.borderColor = "red";
}

return ok;
}

<div data-toggle="buttons" class="btn-group">
<label class="btn active">
<input id = "yes" type="checkbox" name="box" value="yes" />
</i>Yes
</label>

<label class="btn active">
<input id = "no" type="checkbox" name="box" value="no" />No
</label>
</div>




Answer

There are a few problems there:

  1. If you use getElementsByClassName you should use the classname without the dot.
  2. The style property is for the element (while getElementsByClassName returns a list of the elements).
  3. If you only set the color of the border (and not the style and the width) there will be no border.

Here is the correction:

function validate() {
  var ok = true;
  var yes = document.getElementById("yes").checked
  var no = document.getElementById("no").checked;

  if (!yes && !no) {
    ok = false;
    document.getElementsByClassName("btn-group")[0].style.border = '1px solid red';
  } else {
    document.getElementsByClassName("btn-group")[0].style.border = '';
  }
  return ok;
}
<div data-toggle="buttons" class="btn-group">
  <label class="btn active">
    <input id = "yes" type="checkbox" name="box" value="yes" />
    Yes
  </label>

  <label class="btn active">
    <input id = "no" type="checkbox" name="box" value="no" />No
  </label>
</div>

<button onclick="validate()">Validate</button>