javascript - count value of single subject from checkbox's data-id which is in string format separated by commas
问题描述
<div>
<input type="checkbox" id="Q_1_ck1" value="R" data-id="Environmental Science, Physical Education, Agriculture, Yoga, ">
<label class="custom-control-label" for="Q_1_ck1">
<div><small>Listening</small></div>
</label>
</div>
<div>
<input type="checkbox" id="Q_1_ck2" value="E" data-id="Entrepreneurship, Political Science, Agriculture, Business Administration, Salesmanship">
<labe for="Q_1_ck2">
<div><small>Speaking</small></div>
</label>
</div>
<div>
<input type="checkbox" id="Q_1_ck3" value="S" data-id="History, Legal Studies, Mass Media Studies, Home Science, Food Nutrition and Dietetics, Foreign Languages, National Cadet Corps, Yoga">
<labelfor="Q_1_ck3">
<div><small>Helping</small></div>
</label>
</div>
I have a above html code, in which there are values of data-id. Actually i want to count values of each data id.
For example : I want to count values of selected check boxes for yoga. 1st and 3rd checkbox data-id contains yoga, if both 1st and 3rd will be selected then yoga count will be 2. if only one checked then count will be 1.
I was using following code but it returns count only if there is one value in data-id. Now i have multiple values separated by commas.
var yoga = $(".multisteps-form__form input[data-id=Yoga]:checked").length;
解决方案
您可以使用attributeContainsWord ~这将匹配由空格或attributeContains分隔的任何单词*如果选择器的字符串出现在元素属性值中的任何位置,它将选择任何元素。
演示代码:
console.log($("input[data-id~=Yoga]:checked").length)
//or
console.log($("input[data-id*=Yoga]:checked").length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="Q_1_ck1" value="R" data-id="Environmental Science , Physical Education , Agriculture , Yoga " checked>
<input type="checkbox" id="Q_1_ck2" value="E" data-id="Entrepreneurship, Political Science, Agriculture , Business Administration, Salesmanship ">
<input type="checkbox" id="Q_1_ck3" value="S" data-id="History, Legal Studies, Mass Media Studies, Home Science, Food Nutrition and Dietetics, Foreign Languages, National Cadet Corps, Yoga" checked>
推荐阅读
- asynchronous - Vue.js v-show 在 axios 之后不起作用
- database - Laravel(不仅如此)多对多关系 Belongs-To-All
- html - 固定 div 高度:移动设备上滚动未填满屏幕时为 100%
- twilio - 是否可以检测到谁在使用 Twilio Video JS SDK 说话?
- svn - SVN 最佳实践——开发人员的“私有”存储库?
- python - python 中的 Azure 计费 API
- windows-10 - windows 10 家庭基本功能错误
- database - 签名板 将签名存储在数据库中
- c# - T-SQL:合并或更新子表
- c# - Linq通用GroupBy日期和其他字段同时