英文:
Count the number of select boxes with a selected value
问题
我只想数一下表单上具有CSS类"topic"且选定值为"Yes"或"No"而不是"value="""的选择框的数量。我的代码如下,它会计算所有选择框的数量。如何将其限制为只计算"Yes"或"No"的选择框?
//Counts all of them instead of just the Yes/Nos
var countTopic = $('.topic option:selected[value="Yes"], .topic option:selected[value="No"]').length;
alert(countTopic);
<select id="ddlTopic_ACH" class="topic">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
请注意,我修改了代码以只计算具有值"Yes"或"No"的选项。
英文:
I have a bunch of selectboxes on a form all with the CSS class of "topic". I just want to count the number of boxes with a selected value of "Yes" or "No" and not value="". My code below counts every selectbox. How do I restrict this to just Yes or No?
//Counts all of them instead of just the Yes/Nos
var countTopic = $('.topic option:selected').length;
alert(countTopic);
<select id="ddlTopic_ACH" class="topic">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
答案1
得分: 1
You can use the empty selector for this. Well the reverse to be precise
let selectedOptions = $('#ddlTopic_ACH option:not(:empty):selected')
console.log(selectedOptions.length) // 1 --> Yes
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="ddlTopic_ACH" class="topic">
<option value=""></option>
<option value="Yes" selected>Yes</option>
<option value="No">No</option>
</select>
英文:
You can use the empty selector for this. Well the reverse to be precise
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let selectedOptions = $('#ddlTopic_ACH option:not(:empty):selected')
console.log(selectedOptions.length) // 1 --> Yes
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="ddlTopic_ACH" class="topic">
<option value=""></option>
<option value="Yes" selected>Yes</option>
<option value="No">No</option>
</select>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论