Javascript: Onload if checkbox is checked, change li class

只愿长相守 提交于 2019-12-13 08:08:34

问题


I have this code on javascript side:

function changeSelectionStyle(id) {
    if(document.getElementById(id).className != 'yes'){
    document.getElementById(id).className = 'yes';
    }
    else{document.getElementById(id).className = '';}
}

And this on html:

<ul>
  <li id="selectedAuthorities-4_1li" class="">
    <input type="checkbox" id="selectedAuthorities-4_1" name="selectedAuthorities" value="ROLE_ADD_COMMENT_TO_CV" checked="checked" onload="changeSelectionStyle(this.id + 'li');" onclick="changeSelectionStyle(this.id + 'li'); checkFatherSelection(this.id);">

    <a href="#" onclick="document.getElementById('selectedAuthorities-4_1').click(); return false;">  Agregar comentario <samp><b></b>Permite agregar comentario en el detalle.</samp>
    </a>
 </li> 

Well what I cant get work is when the checkbox is selected, on load, the JS should check it, and assign class="yes" to the li, here: <li id="selectedAuthorities-4_1li" class="">

What should I add to my original JS function to make that possible. Note that li ids are not static, they are dynamic, the html li id is generated.

Process for the solution (logic):

Event on load, check if the input with X id is checked, if it is, update the parent li with the JS function changeSelectionStyle. Because the problem that I have right now, is that when I select an input (check it), the li color is switching, but when it loads with a selected/checked input, the color remains untouched, and its changing the color when I click the input (uncheck it - wrong effect)


回答1:


window.onload=function(){
var inputFields=document.getElementsByTagName('input');
var checkBoxes[];
for(var i=0;i<inputFields.length;i++)
 if(inputFields[i].type=='checkbox'&&inputFields[i].checked=='checked'&& inputFields[i].parentNode.tagName=='LI')
inputFields[i].parentNode.className='yes';
}

Here we go..



来源:https://stackoverflow.com/questions/2819814/javascript-onload-if-checkbox-is-checked-change-li-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!