How to loop through group of check boxes that have same class name?

你说的曾经没有我的故事 提交于 2020-01-07 03:01:07

问题


I have dynamic table that has table cell with checkbox field. This fields are populated from DB so my table is dynamic. I would like to loop through checkboxes based on their class name. In that loop I want to check value for each check box. For example if value is equal 1 I want checkbox to be checked, if not unchecked. Alo I'm not sure if possible but I would like to set unique ID for each of these check boxes. Since my table is dynamic my fields need to have unique ID's. Here is example of my code:

<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Time Slots</th>
            <th>Block</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td>~(SLOT_LABEL)</td>
            <td>
                <span>
                <input type="checkbox" name="CF-[Events]" class="block" id="block_"+Value that will make this ID unique. value="~(SLOT_ID)"/>
                </span>
            </td>
        </tr>
    </tbody>
</table>

Also in current language that I work with to read values from DB I have to use NAME tag. If anyone can help please let me know. Thank you.


回答1:


You can use the attribute selector to retrieve elements by both their name and value. Try this:

$('input[name="CF-[Events]"][value="1"]').prop("checked", true);

Working example




回答2:


If you don't want a jQuery solution, it is also possible to fetch these elements with the querySelector:

var inputs = document.querySelectorAll("input.block");
for(var i = 0; i < inputs.length; i++) {
  inputs[i].checked = true;
}



回答3:


you can do it in jquery by each loop

$('.ClassName').each(function(i, o) {
    // o is object in your case checkbox    
    // i is index
    // your code
});



回答4:


$("input[name='CF-[Events]']").each(function() {
   if($(this).val() === "1")
   {
       $(this).prop("checked", true);
   }
});


来源:https://stackoverflow.com/questions/35506843/how-to-loop-through-group-of-check-boxes-that-have-same-class-name

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