繁体   English   中英

选中和取消选中时如何为html中的复选框分配值?

[英]How to assign values to checkbox in html when check and uncheck?

我的HTML表单中有一个HTML复选框。 现在,我想在选中时分配1,在不选中时分配0。 那么,我该如何使用jquery或java脚本呢?

<!DOCTYPE html>
<html>

  <script language="javascript" type="text/javascript">
  <!--
  function greeter() {
      alert(document.getElementById(vehicleChkBox).value);
  }
  $('#vehicleChkBox').change(function(){
       if($(this).attr('checked')){
            $(this).val(1);
       }else{
            $(this).val(0);
       }
  });
  </script>
  <body>
    <form>
      <input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE" />
      <input type="submit" onsubmit="greeter()">
    </form>
  </body>

我尝试了这个。 但是,不起作用。

JS:

var checkbox = document.querySelector("input[type='checkbox']");
  checkbox.addEventListener("change",function(){
     this.value = this.checked ? 1 : 0;
  });

jQuery的:

$(":checkbox").change(function(){
     $(this).val($(this).is(":checked") ? 1 : 0);
});

您可以将JQuery用于change事件:

 $(function() { $('#vehicleChkBox').on('change', function(e) { e.stopPropagation(); this.value = this.checked ? 1 : 0; }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="vehicle" id="vehicleChkBox" value="0" /> 

您只需要将其值设置为1。这样,当它被选中时将返回1,而在未被选中时将不返回任何内容,因此您可以进行检查并分配零。

<input type="checkbox" name="my_checkbox" value="1" />

我正在使用此,这绝对正常:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");

注意:如果选中此复选框,它将返回true,否则未定义,因此最好检查“ TRUE”值。

要么

if(!$("#checkkBoxId").is(':checked') ){
 $(this).val('1');
}
else
$(this).val('0');

这将很好地设置值

   $("#checkkBoxId").prop("checked") ? ($("#checkkBoxId").val(1)) :    ($("#checkkBoxId").val(0));
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script> 
   $(document).ready(function() {
         $('#vehicleChkBox').click(function(){
             if($(this).is(':checked'))
             {              
                  $(this).val('1');
             }
             else
             {
                 $(this).val('0');
             }
         });
    });
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM