Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following HTML containing a drop down list (single selection)

        <script type="text/javascript">
            $(document).ready(function () {
                $("#garden").bind('change', function() {
                    alert("Changed");
                    });
            });
        </script>
    <body>
        <div id="content">  
           <select id="garden">
             <option value="flowers">Flowers</option>
             <option value="shrubs">Shrubs</option>
             <option value="trees">Trees</option>
             <option value="bushes">Bushes</option>                 
           </select>
        </div>
    </body>
</html>

When the HTML page is rendered, Flowers is the already selected element in the drop-down by default (being the first one). If I select any other value (other than "Flowers"), the Javascript function is fired and a alert box containing "Changed" is shown.

Q1: But, in case I re-select Flowers again, the onchange event is not triggered. I understand it is because nothing was 'changed' in the drop-down list. Is there a way a function is triggered even when no change to the already selected value in drop-down is done?

Q2: How to extract the value of the element which has just been selected (even if nothing new was selected - that is, user clicked on the drop down, and simply clicked somewhere else).

I have already tried the onblur but that requires that the user clicks somewhere else on the document so that the drop-down loses focus. Any help would be really appreciated.

[I have edited out the HTML headers and other script inclusions in the code snippet provided for brevity.]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
305 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well I think I don't get you 100%, but some things I can suggest here are:

  • bind a click event handler to the select

    $("#garden").bind('click', function() {
         alert($(this).find('option:selected').text());
    });
    
  • bind a focusout event handler

    $("#garden").bind('focusout', function() {
         alert($(this).find('option:selected').text());
    });
    

and of course bind the change event handler which you already got. The click event handler might be a little bit tricky since it would fire every time you click on the element. But if you don't alert() it every time it should not be a problem at all, you got the current selection and can do with it whatever you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...