简体   繁体   English

检测是否选中了复选框,然后获取div ID

[英]Detect if a checkbox is checked, then get div id

I have checkboxes on a page, when you click a span for each checkbox, it will change the background color of the containing div for each checkbox. 我在页面上有复选框,当您单击每个复选框的跨度时,它将更改每个复选框所含div的背景颜色。 The problem is when someone submits the form and goes to the following page, then clicks the back button the checkboxes remain checked but the div color reverts. 问题是当有人提交表单并转到下一页,然后单击“后退”按钮时,复选框保持选中状态,但div颜色恢复。 Is there a way to get the div ids of checked boxes when the page loads? 页面加载时,是否可以获取复选框的div ID?

I have this to detect checked boxes in by body onload, but not sure how to get div id for each of them: 我有这个可以通过body onload来检测复选框,但是不确定如何获取每个复选框的div ID:

function detectchecked(){
  var count = 0;
  var inputs = myform.getElementsByTagName('input');
  for (var i = 0, j = inputs.length; i<j; i++) {
      var input = inputs[i];
      if (input.type && input.type === 'checkbox' && input.checked) {
          alert(input);
      }
   }
  }

My current code for the inputs looks like this: 我当前输入的代码如下所示:

<div id="myform">
 <div id="div4452101" style="float:left; width:194px; height:90px; border:1px solid #000; margin:2px;"> 
  <div class="resultphoto"> 
   <span onClick="checkem('4452101');"> 
    image goes here
   </span>
  </div> 
  <span onClick="checkem('4452101');"> 
   check this
  </span> 
  <input type="checkbox" name="numbers[]" id="4452101" value="4452101" /> 
 </div>
</div>

There is no need for jQuery in such a codeless and easy questions. 在这种无代码和简单的问题中,不需要jQuery。

You must use code like this: 您必须使用如下代码:

function detectchecked(){
  var count = 0;
  var inputs = myform.getElementsByTagName('input');
  for (var i = 0, j = inputs.length; i<j; i++) {
      var input = inputs[i];
      if (input.type && input.type === 'checkbox' && input.checked) {
          document.getElementById('div'+input.getAttribute('id')).setAttribute('style','Your style here');
      }
   }
  }

Of course, if i understood you correctly 当然,如果我理解正确

Did you think to use a framework ? 您是否认为要使用框架? JQuery ? jQuery的?

That script gonna be easy : 该脚本将很容易:

$('#myform input[type=checkbox]:checked').attr('style','your style'); $('#myform input [type = checkbox]:checked')。attr('style','your style');

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

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