统计具有选定值的选择框数量。

huangapple go评论62阅读模式
英文:

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 = $(&#39;.topic option:selected&#39;).length;
    alert(countTopic); 
	
	&lt;select id=&quot;ddlTopic_ACH&quot; class=&quot;topic&quot;&gt;
		&lt;option value=&quot;&quot;&gt;&lt;/option&gt;
		&lt;option value=&quot;Yes&quot;&gt;Yes&lt;/option&gt;
		&lt;option value=&quot;No&quot;&gt;No&lt;/option&gt;
	&lt;/select&gt;  

答案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 = $(&#39;#ddlTopic_ACH option:not(:empty):selected&#39;)

console.log(selectedOptions.length) // 1 --&gt; Yes

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;select id=&quot;ddlTopic_ACH&quot; class=&quot;topic&quot;&gt;
      &lt;option value=&quot;&quot;&gt;&lt;/option&gt;
      &lt;option value=&quot;Yes&quot; selected&gt;Yes&lt;/option&gt;
      &lt;option value=&quot;No&quot;&gt;No&lt;/option&gt;
  &lt;/select&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月26日 22:22:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定