Selection of a group of dropdown box values using each statement in jquery

1.3k views Asked by At

I want to write a simple code in Velocity Template Language (VTL). I have a group of dropdowns, I want iterate through all the dropdowns and get the values of each dropdown and count the number of selected values under each distinct category. The code is listed below:

#macro( macroYesNoSelect $fieldId $section )
<select  name='${fieldId}' id='${fieldId}' section='${section}' ischanged="">
    <option value="Yes" 
        #if ($Form.getFieldValue("${fieldId}") == "Yes") 
            selected 
        #end 
    score="1">Yes</option>
    <option value="No"  
        #if ($Form.getFieldValue("${fieldId}") == "No") 
            selected 
        #end
    score="0">No</option>
    <option value="N/A" 
        #if ($Form.getFieldValue("${fieldId}") == "N/A") 
            selected 
        #end
    score="0">N/A</option>
</select>
#end

Javascript:

<script>
calcYesNO("Question");

function calcYesNO(sectionName){
        var scoreSum=0;
        var optionYes=0;
        var optionNo=0;
        var optionNA=0;
        $("select[section='"+ sectionName +"']").each(function(){

         if($(this).find("option:selected").attr('value') == 'Yes')
         {
          optionYes=optionYes+1;
         }
         else if($(this).find("option:selected").attr('value') == 'No')
         {
          optionNo=optionNo+1;
         }
         else
         {
          optionNA=optionNA+1;
         }      
        } 
        scoreSum = optionYes;
        return scoreSum;
        }

</script>

HTML code:

<table>
<tr>

        <td>Question1 ?</td>
        <td>
            #macroYesNoSelect ( "id1" "Questions" )
        </td>

    </tr>
    <tr>

        <td> Question2 ?</td>
        <td>
            #macroYesNoSelect ( "id2" "Questions" )
        </td>
    </tr>
    <tr>

        <td> Question3 ?</td>
        <td>
            #macroYesNoSelect ( "id3" "Questions" )
        </td>
    </tr>
</table>

I want to select the number of YES, NO and NA as per my selection. But when I call the function calcYesNO(), I am unable to calculate them...

Can someone help me on resolving this? Thanks Kishore

1

There are 1 answers

0
Luke Dennis On

jQuery is smart about retrieving <select> values; you can call .val() directly. I also recommend being more explicit with the each() iterator, since the "this" keyword can have unexpected values in certain circumstances.

$("select[section='"+ sectionName +"']").each(function(n, element){

     if($(element).val() == 'Yes')
     {
      optionYes=optionYes+1;
     }
     else if($(element).val() == 'No')
     {
      optionNo=optionNo+1;
     }
     else
     {
      optionNA=optionNA+1;
     }      
    }

That said, your existing code looks like it should work. Have you verified that $("select[section='"+ sectionName +"']") is actually retrieving the select menu?