Event listener inside a function

时间:2016-04-25 09:44:22

标签: javascript jquery events

I have a select on my page:

<select id='cat'>
    <option value='a'>A</option>
    <option value='b'>B</option>
    <option value='all'>all</option>
</select>

With a javascript function that handles which options have to be displayed:

function funcName(aList) {
    // populates the options for the select tag
    $("#cat").on("change", function(){
        // some computation;
    });
    // uses aList to update some div data
 }

What I'm trying to do is if the selected option is all, I have to display everything in aList, otherwise based on the selected option I have to display only the related options. Is my usage of onchange event correct?

Initially I thought of making aList global, but after some reading on globals in JS, I got to know it is not a very good practice.

Thanks in advance!

UPDATE: aList contains some string values.

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
$(function () {
        $("#ddl").change(function () {
            var selectedText = $(this).find("option:selected").text();
            var selectedValue = $(this).val();
          var assignedRoleId = new Array();
          alert("Selected Text: " + selectedText + " Value: " + selectedValue);
          if(selectedValue== "all")
            {
              $("#ddl option").each(function()
                  {
                if(this.value=="all")
                  {
                    assignedRoleId.push();
                  }
                else
                  {
                    assignedRoleId.push(this.value);
                     assignedRoleId.push(" ");
                    $("#selected").html(assignedRoleId);
                    }
                 });
            }
         });
    });
&#13;
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Select something:
<select id="ddl">
    <option value="">select one</option>
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="all">all</option>
</select>
<div id="selected">
  </div>
&#13;
&#13;
&#13;