复选框值是/否 [英] Checkbox value true/false

查看:77
本文介绍了复选框值是/否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有复选框的表单,并且在提交带有错误的同一个视图时,我想在提交表单后保持选中状态.我听说value属性可以帮助我选中该复选框,因此我试图将其设置为true/false.无论如何,即使我单击输入值,它也保持"false".到底会发生什么? 我认为点击复选框后值会变为true/false

I have a form with checkbox and I want to keep it checked after submitting the form when it goes back to the same view with an error. I heard that the value attribute can help me to make the checkbox be checked so im trying to set it to true/false. Anyway, the input value stays "false" even if I click it. What happens exactly? I thought the value goes true/false after clicking the checkbox

<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">

      <script>
          $("#checkbox1").is(':checked', function(){
              $("#checkbox1").attr('value', 'true');
          });
      </script>

推荐答案

如果我理解这个问题,则希望根据是否选中该复选框来更改该复选框的值.

If I understand the question, you want to change the value of the checkbox depending if it is checked or not.

这是一种解决方案:

$('#checkbox-value').text($('#checkbox1').val());

$("#checkbox1").on('change', function() {
  if ($(this).is(':checked')) {
    $(this).attr('value', 'true');
  } else {
    $(this).attr('value', 'false');
  }
  
  $('#checkbox-value').text($('#checkbox1').val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">

<div id="checkbox-value"></div>

这篇关于复选框值是/否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆