getSelectedValues函数

getSelectedValues函数

好的,所以我有这段代码,可以选择并计算已选择特定选项的选择框的数量。但是,我想将其更改为组。我有3组下拉菜单,它们目前在

<div class"groupA">


等等

我要做的是从每个组中获取计数。如何修改此脚本以仅计算页面上特定组中的选定脚本?现在可以使用,但会计算整个页面上选择了多少个。

<script type="text/javascript">


function getSelectedValues(){
  var matches = $('select').filter(function(){
  return $(this).val() == '5';
  }).length;
  // here's where we just update that new <span>
  $('span#result5').text(matches);
}

// and here we bind to the change event for the selects
// and re-call our above function.
$('select').on('change', getSelectedValues);

   </script>


 <span id="result5"></span>


其次,现在span ID = result显示选择特定选项的次数。相反,如果计数超过1,我希望它将文本颜色更改为红色。因此,这是我要执行的操作的较差示例:

<span id="result5"></span>

This select name <-- how it displays when 0, or 1 are selected

<font color="#FF0000">This select name</font>
    ^-- how it displays when 2 or more are selected

最佳答案

若要仅选择组中的“选择”,请尝试通过以下方式选择它们:

var matches = $('.groupA select')...


要将其更改为红色,请尝试以下操作:

// here's where we just update that new <span>
if(matches > 1){
    $('span#result5').css( "color", "red" );
}
$('span#result5').text(matches);


我希望我能帮上忙

关于javascript - javascript getSelectedValues函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28700980/

10-11 12:12