3

I have a select box with some dates. I want to get the value of said dates when the input changes. I keep getting undefined for my value.

$('#date_pick').change(function(){
            var values = $('#date_pick:selected').val();
            alert(values);
});

Fiddle

gdoron
  • 147,333
  • 58
  • 291
  • 367
Bri
  • 729
  • 2
  • 17
  • 38
  • Wow, thanks everyone. I must be really out of it today. As soon as I saw these solutions I knew...I KNEW! D: – Bri Mar 19 '12 at 14:24
  • I just want to clarify that, getting the value of a ` – gdoron Mar 19 '12 at 18:44
  • ^ Just to clarify, that wasn't working out for me for some odd reason so I went the route I did. – Bri Mar 28 '12 at 15:53

7 Answers7

12

You need to put a space between the #date_pick and :selected.

var values = $('#date_pick :selected').val();

Fiddle: http://jsfiddle.net/PJT6r/9/

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
3

Getting the value of a <select> element (just like every other form element), is done with the val() function.

So in your case => $('#date_pick').val().

Note that in the change callback scope you don't need to re-select the element, this inside a callback is the DOM element that triggered the callback:

$('#date_pick').change(function() {
    alert($(this).val());
});

LIVE DEMO

gdoron
  • 147,333
  • 58
  • 291
  • 367
1

you have to remove the 'selected'!

var values = $('#date_pick').val();

It's a caffeine issue, I'm sure.

Alejandro B.
  • 4,807
  • 2
  • 33
  • 61
1

or just var values = $(this).val();

Manatok
  • 5,506
  • 3
  • 23
  • 32
1

You don't need the :selected bit in your selector Use:

$(function(){
        $('#date_pick').change(function(){
                    var values = $('#date_pick').val();
                    alert(values);
        });
});

gdoron
  • 147,333
  • 58
  • 291
  • 367
Mick Sear
  • 1,549
  • 15
  • 25
  • Bit of an easy one. I can see why people get confused with this though, because radio buttons and checkboxes don't work in quite the same way as select boxes. – Mick Sear Mar 19 '12 at 14:19
1

You can;

 var values = $('#date_pick option:selected').val();
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

I was getting undefined/null values when trying to get value by ID. So I tried to get the selected value by select field Name.

<select name="date_pick" id="date_pick">
</select>

Then in jQuery,

$("select[name=date_pick]").val();

And result NOT Getting undefined / null.

G_real
  • 1,137
  • 1
  • 18
  • 28