Home > database >  Can't get Toggle Switches to work in Asp.Net Webforms
Can't get Toggle Switches to work in Asp.Net Webforms

Time:07-19

I need to add a toggle switch that I can read from and set to tell me whether the user wants this activated or disabled.

I have this CSS which I have found in multiple different examples

    .switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked   .slider {
  background-color: #2196F3;
}

input:focus   .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked   .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

and using this HTML

    <label >
    <input type="checkbox">
     <span ></span>
     </label>

But when I actually test it, it renders the HTML like this, which causes the toggle switches not to work Screenshot

The line marked in red is being added from somewhere and I can only see it if I go to inspect the element in chrome. I have no clue why this is happening, if I remove the line in question then the toggle switch will work as expected

I hope someone has a solution to this problem that has been bothering me for so long

CodePudding user response:

In the CSS the next-sibling combinator ( ) is used to set the checked styles on the .slider span. It will not match if HTML is generated by ASP controls as in your example when using <asp:CheckBox ... /> instead <input type="checkbox">, as there is a HTML element between the input and the .slider (so there is no next-sibling relation), which you also pointed out. To still get a match in that case, the subsequent-sibling combinator (~) can be used instead the next-sibling combinator in the selectors of the checked styles.

  • Related