表格提交JSP之后,请保留检查/未选中的复选框状态



我的表单中有某种复选框,默认情况下会检查。我想做的是在取消选中复选框并单击"提交"按钮时,请致电JavaScript函数以更改复选框的值,并且它的状态也(检查/未检查)。

那是我尝试的方法,但没有按预期工作?

  <form action="ResultServlet" method="post" id="searchForm">
     <table cellspacing="0" style="width: 50%;float: right">
         <tr>
           <th style="text-align: left;"><label>Work List Cases:</label></th>                       
            <td>
              <div class="checkbox checkbox-primary">
                <input name="workListCases" id="checkbox2" checked type="checkbox" value="">
                 <label for="checkbox2"></label>
              </div>
            </td>
         </tr>
    </table>
      <button type="submit" onclick="changeCheckBox()" style="font-weight: bold;background-color: #F0F1F2" class="btn btn-default">Search</button>                        
  </form>

JS功能:

 function changeCheckBox (){
           if($("#checkbox2").is(':checked')){
                $("#checkbox2").val("true");
                $('#checkbox2').attr('checked', false);
            }
            else {
                $('#checkbox2').attr('checked', true);
                $("#checkbox2").val("true");
            }
        }

请原谅我的问题是否似乎很乏味,我还是jQuery的新手。

默认情况下您的复选框value ="" ...

为什么值"true""false"

尝试:

function changeCheckBox (){
           if($("#checkbox2").is(':checked')){
                $('#checkbox2').attr('checked', false);  //jquery <1.6
                $('#checkbox2').removeAttr('checked');
                $('#checkbox2').prop('checked', false); //jquery >1.6
                $('#checkbox2').removeProp('checked');
            }
            else {
                $('#checkbox2').attr('checked', true);
                $('#checkbox2').prop('checked', true);
            }
}

最新更新