Trafalgar D Law Trafalgar D Law - 1 month ago 4
Javascript Question

How to apply my class from css to checkbox?

I have this working code but why the checkbox is not affecting it?.



$("#btn").click(function() {
if ($("#txt2").val() == 2) {
alert("Hello");
$("#txt").removeClass('validation');
$("#chk").removeClass('validation');
} else {
$("#txt").addClass('validation');
$("#chk").addClass('validation');
}
});

.validation {
border: 1px solid #ff0000;
background-color: #ffeeee;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<input type="checkbox" id="chk">
<input type="text" id="txt">
</td>
</tr>
<input type="text" id="txt2">
<input type="button" id="btn" value="Click">





Anyone know about this issue or problem?.

Answer

Your checkbox is getting the class (you can tell in the DOM inspector); you don't see the styling because the checkbox border isn't shown.

Some of the answers to this question suggests using outline rather than border for checkboxes; see the new style rule in the example below.

$("#btn").click(function() {
  if ($("#txt2").val() == 2) {
    alert("Hello");
    $("#txt").removeClass('validation');
    $("#chk").removeClass('validation');
  } else {
    $("#txt").addClass('validation');
    $("#chk").addClass('validation');
  }
});
.validation {
  border: 1px solid #ff0000;
  background-color: #ffeeee;
}
input[type=checkbox].validation {
  outline: 1px solid #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <input type="checkbox" id="chk">
    <input type="text" id="txt">
  </td>
</tr>
<input type="text" id="txt2">
<input type="button" id="btn" value="Click">

Comments