获取切换复选框状态是真还是不

时间:2017-11-29 12:29:26

标签: jquery checkbox toggle status

在此,我没有得到复选框的状态是真还是假我尽我所能我没有得到任何解决方案。当点击切换时,它总是给我一个假值

input[type=checkbox] {
  width: 0;
  height: 0;
  visibility: hidden;
}

label {
  cursor: pointer;
  text-indent: -9999px;
  width: 50px;
  height: 20px;
  background: grey;
  display: block;
  border-radius: 100px;
  position: relative;
}

label:after {
  content: '';
  position: absolute;
  top: 3px;
  left: 3px;
  width: 14px;
  height: 14px;
  background: #fff;
  border-radius: 90px;
  transition: 0.3s;
}

input:checked+label {
  background: #bada55;
}

input:checked+label:after {
  left: calc(100% - 5px);
  transform: translateX(-100%);
}

label:active:after {
  width: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="toggle" id="switch">
<label for="switch">Toggle</label>
const PageLayoutRoute = ({component: Component, ...rest }) => {
  return (
  <Route
    {...rest}
    render={props =>
      <PageLayout {...props}>
        <Component />
      </PageLayout>}
  />
  )
};

2 个答案:

答案 0 :(得分:2)

问题在你的选择器中。您需要更改代码中'的位置..!

$('input').on("change", function() {
    if ($('input[type="checkbox"]').is(":checked")) { //or you can use $(this) instead of $(input[type="checkbox"]) to select itself
    alert("its checked");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="toggle" id="switch">
<label for="switch">Toggle</label>

答案 1 :(得分:0)

使用$(this).is(":checked")代替。

$('input').on("change", function () {
    if ($(this).is(":checked")) {
        alert("its checked");
    }
});
input[type=checkbox] {
    width: 0;
    height: 0;
    visibility: hidden;
}

label {
    cursor: pointer;
    text-indent: -9999px;
    width: 50px;
    height: 20px;
    background: grey;
    display: block;
    border-radius: 100px;
    position: relative;
}

label:after {
    content: '';
    position: absolute;
    top: 3px;
    left: 3px;
    width: 14px;
    height: 14px;
    background: #fff;
    border-radius: 90px;
    transition: 0.3s;
}

input:checked + label {
    background: #bada55;
}

input:checked + label:after {
    left: calc(100% - 5px);
    transform: translateX(-100%);
}

label:active:after {
    width: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="toggle" id="switch">
   <label for="switch">Toggle</label>

有一点,你不需要将widthheight设置为零,只需使用visibility

input[type=checkbox] {
    /* width: 0; */
    /* height: 0; */
    visibility: hidden;
}