JQuery get selected dropdown value when changing

I am trying to get the value of a dropdown when changing (and then change the values ​​in the second drop down).

EDIT: Thanks for all the answers, I updated to add (), but the code returns nothing, not null or undefined just an empty warning window

However, when I warn about this, the value of attr (value) is undefined.

Any ideas on what I am missing?

Here is my code:

<script type="text/javascript">
            $(document).ready(function() {

                var roomID = "0"
                $('.dropone').load('ajaxdropdown.aspx');
                $('.droptwo').load('ajaxdropdown.aspx?drpType=room&roomid=' + roomID);

                $('.dropone').change(function() {
                var ts = new Date().getTime();
                alert($(this).val)

                    $(".droptwo").empty();
                    $(".droptwo").load("ajaxdropdown.aspx?drpType=room&roomid=" + $(this).attr("value") + "&ts=" + ts);
                });

            });        
        </script>
+5
source share
5 answers

val is a method, not a property.

use it like val()

If you use it in many places, I would assign it to a local variable and subsequently use it.

$.now(), . DategetTime();

$('.dropone').change(function() {    
    var item=$(this);
    alert(item.val())
    $(".droptwo").empty();
    $(".droptwo").load("ajaxdropdown.aspx?drpType=room
                        &roomid=" +item.attr("value") + "&ts=" + $.now());
});
+12
$('.dropone').change(function() {
  var val = $(this).val(); 

  // OR

  var val = this.value;
})
+9

You should get the value using a method, not a property. Use this:

alert($(this).val())
+4
source

Add parentheses to your val: alert($(this).val())

+1
source

You can also get custom attributes from the drop-down list, as shown below:

     $('.someclass').change (function () { 
              var val = this.value;
              alert(val);                                       //selected value

               var element = $(this).find('option:selected');  // assign selected element
               var myTag = element.attr("aTag");              // get attribute by name
               alert(myTag);
    });


<option name='somename' id='someid' aTag='123' value='XYZ'>XYZ</option>
0
source

All Articles