开发者

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. 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. Is there a way to get the div ids of checked boxes when the page loads?

I have this to detect checked boxes in by body onload, but not sure how to get div id for each of them:

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.

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 ?

That script gonna be easy :

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜