Liam Potter
Liam Potter

Reputation: 1824

HTML Select Option Value Not Updating

I have a HTML form with the following select element in it:

<select class="form-control" onchange="$('form#filter').submit()" id="sort" name="sort">
    <option value="0" selected="selected">A - Z</option>
    <option value="1">Z - A</option>
</select>

The issue is that when I select a different option, the HTML doesn't update and set the option I chose as the selected option.

I have absolutely no idea why it isn't updating and I've been at it for hours now.

This is the function that is bound to the submit event on the form in case you need it:

$("form#filter").on("submit", function(evt)
{
    var form = $(this);
    var target = $("div#bands");

    var url = form.attr("action") + "/" + form.find('option[selected]').val();
    console.log(url);

    $.get(url).done(function(data)
    {
        target.html(data);
    });

    evt.preventDefault();
});

Upvotes: 1

Views: 12982

Answers (2)

Henrik Erlandsson
Henrik Erlandsson

Reputation: 3830

The accepted answer is incorrect. Here is a correct solution (tested on latest JQuery and Bootstrap at time of writing):

$("#mySelect").find("option:selected").val();

Thanks to Barmar for the inspiration, though only 1 of the 4 suggestions works, and only by accident. But I adapted that to log out the correct value attribute for the currently selected option. (The selected state of the initial option does not update when using the dropdown, see Chris O'Kelly's comment.)

Upvotes: 0

Barmar
Barmar

Reputation: 782693

Change

form.find("option[selected]").val()

to

form.find("option:selected").val()

or:

form.find("select").val()

or:

$("#sort").val()

The selector option[selected] doesn't find the option that's currently selected, it finds the option that has the selected attribute in the DOM (this is normally the one with the selected attribute in the HTML, although it's possible to change it using Javascript).

Upvotes: 3

Related Questions