jQuery: The Write Less, Do More JavaScript Library

changing a select

View: New views
2 Messages — Rating Filter:   Alert me  

changing a select

by Mark Volkmann-3 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I need to programmatically change the option that is selected within a select.
I have code registered to run when this occurs, whether the selection
is initiated by the user or programmatically.
Why doesn't this approach work?

$(document).ready(function () {
  $("select#foo").change(function () {
    alert("Now selected: " + $("select#foo > option:selected").text());
  }
}

var select = $("select#foo");
select.find("option:first").select();
select.change();

The alert is only displayed when the user changes the selection, not
when the code above changes it.

--
R. Mark Volkmann
Object Computing, Inc.

Re: changing a select

by James-279 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Try this:

var $select = $("select#foo"),
    firstVal = $select.find('option:first').val();
$select.val(firstVal).change();

On Nov 3, 7:43 am, Mark Volkmann <r.mark.volkm...@...> wrote:

> I need to programmatically change the option that is selected within a select.
> I have code registered to run when this occurs, whether the selection
> is initiated by the user or programmatically.
> Why doesn't this approach work?
>
> $(document).ready(function () {
>   $("select#foo").change(function () {
>     alert("Now selected: " + $("select#foo > option:selected").text());
>   }
>
> }
>
> var select = $("select#foo");
> select.find("option:first").select();
> select.change();
>
> The alert is only displayed when the user changes the selection, not
> when the code above changes it.
>
> --
> R. Mark Volkmann
> Object Computing, Inc.