0

I have a button that, when clicked, should get me the value of a combo box's selected item. For example, if I have the following combo and button:

<select id="client-sort-type">
    <option></option>
    <option>Name</option>
    <option>Recent</option>
</select>

<button id="client-sort-submit" type="button">Sort</button>

I want something like...

<script type="text/javascript">
    $("#client-sort-submit").click(function () {
        var val = $("#client-sort-type").attr("value");
        window.location.href = "Project/Index/" + val;
    });
</script>

Only this isn't working, it always returns nothing. Help?

ElliotSchmelliot
  • 6,236
  • 3
  • 37
  • 62
  • 1
    [link](http://stackoverflow.com/questions/1643227/get-selected-text-from-dropdownlist-using-jquery) This question has the answer you are looking for. – Ellesedil Aug 13 '13 at 19:30
  • Your markup is not correct, please check my answer. – Sergio Aug 13 '13 at 19:41

3 Answers3

1

Well for starters you should have value= in your <options>, otherwise it might generate unwanted behaviours.

Use <option value="somevalue" >Name</option>

If you want to get the value via jQuery you should use:

$("#client-sort-type").val(); // this will give you "somevalue"

If you want to get the text of the selected option use:

$("#client-sort-type option:selected").text(); // This will give you "Name"

Read the difference between this and this, if you keep your html as it is, it's better to use .text()

Community
  • 1
  • 1
Sergio
  • 27,998
  • 10
  • 81
  • 130
0

Use

$("#client-sort-type").val()
asymptoticFault
  • 4,471
  • 2
  • 18
  • 23
0

Instead of

val = $("#client-sort-type").attr("value");

use

val = $("#client-sort-type").val();
mavili
  • 3,265
  • 4
  • 29
  • 45