获取已检查引导程序复选框的值

时间:2016-08-25 18:46:38

标签: javascript jquery html

我有这个HTML表单:

<div class="animated-switch">
  <input id="switch-success" name="switch-success" checked="" type="checkbox">
  <label for="switch-success" class="label-success"></label>
</div>  

我怎么知道输入是否被检查?

我试过这样但没有提醒:

$(document).on('click','.animated-switch',function(e){
    alert($('#switch-success:checked').val() );
});

这是一个JSFIDDLE文件,以便查看我的明确示例:https://jsfiddle.net/s2f9q3fv/

4 个答案:

答案 0 :(得分:8)

如果选中该复选框,则会得到。

       $('#' + id).is(":checked")

答案 1 :(得分:4)

您的代码在代码段中运行良好。您忘记为复选框添加值,但即使没有它,您也应该能够看到具有未定义值的警报消息(请参阅下面的代码片段中添加的值'test')。

$(document).on('click','#switch-success:checked',function(e){
    alert($('#switch-success:checked').val() );
});
.animated-switch > input[type="checkbox"] {
  display: none; }

.animated-switch > label {
  cursor: pointer;
  height: 0px;
  position: relative;
  width: 40px; }

.animated-switch > label::before {
  background: black;
  box-shadow: inset 0px 0px 10px rgba(0, 0, 0, 0.5);
  border-radius: 8px;
  content: '';
  height: 16px;
  margin-top: -8px;
  position: absolute;
  opacity: 0.3;
  transition: all 0.4s ease-in-out;
  width: 40px; }

.animated-switch > label::after {
  background: white;
  border-radius: 16px;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3);
  content: '';
  height: 24px;
  left: -4px;
  margin-top: -8px;
  position: absolute;
  top: -4px;
  transition: all 0.3s ease-in-out;
  width: 24px; }

.animated-switch > input[type="checkbox"]:checked + label::before {
  background: inherit;
  opacity: 0.5; }

.animated-switch > input[type="checkbox"]:checked + label::after {
  background: inherit;
  left: 20px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="animated-switch">
  <input id="switch-success" name="switch-success" checked="" value="test" type="checkbox">
  <label for="switch-success" class="label-success"></label>
</div>

<强>更新: 您应该在复选框本身而不是父对象上绑定click事件。用花哨的动画再次尝试剪切。 请注意,如果您希望始终执行警报,则必须删除选择器中的:checked属性。

答案 2 :(得分:0)

试试这个

$(".animated-switch").change(function () {
    alert($('#switch-success:checked').val() );
    });

答案 3 :(得分:0)

我仍然遇到问题,并想出了一种解决方法:

<input class="form-check-input" type="checkbox" id="inlineCheckbox1" 
onclick="document.getElementById('inlineCheckbox1').setAttribute('value', 
document.getElementById('inlineCheckbox1').value * -1)" value='-1'>
<label class="form-check-label" for="inlineCheckbox1">1</label>

我设置了一个'onclick'事件,并将'value'属性设置为-1。当您单击复选框或标签时,“值”将更改其符号。因此,当您想要获取值时,请抓住“值”属性,并检查它是否大于或小于零。

相关问题