jQuery function to highlight drop down list not working

I had an HTML select control generated from MVC Razor:

@Html.DropDownList("coasters", (List<SelectListItem>)ViewBag.Coasters, "--Select--", new { @class = "form-control")

I had a jQuery method that was supposed to highlight the drop down list value using the “val” method:

function loadCoaster(coaster) {
        $('#coasters').val(coaster);
}

But it wasn’t working. The value in the drop down list would flash briefly, then disappear.

What I found worked was setting the “selected” attribute by using jQuery’s “attr” method:

function loadCoaster(coaster) {
        $('select[name^="coasters"] option[value="' + coaster + '"]').attr("selected", "selected");
}

Using this, the value stuck.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: