-1

In my web page I use something like this, but when a option is selected, onchange is not fired. I don't know where I have made a mistake. Actually my requirements is that I need to fetch location details based on the city selected, but it is not working here. Is there any other better way to do so?

 @Html.DropDownList("cities", ViewBag.cities as SelectList, new { onselect = "getLoca();"});    
<script type="text/javascript">
function getLoca() {
    alert("yes");
    $.post('@Url.Action("getLocations","Home")', { 'id': $("#cities").val() },
        function (data) {
            $("#loca").html(data).show();

        });
}
</script>

EDIT:
This is the generated HTML code

 <select id="cities" name="cities" onselect="getLoca()"><option value="0">--City--     </option>
<option value="1">City1</option>
<option value="2">City2</option>
<option value="3">City3</option>
<option value="4">City4</option>
<option value="5">City5</option>
</select>;                   
<select id="loca" name="loca" style="width: 170px" ></select>
John
  • 1
  • 13
  • 98
  • 177
pavan
  • 34
  • 2
  • 10

1 Answers1

1

Use onchange instead of onselect.

jsFiddle Demo

onselect does not do what you expect - it fires when the user selects text (you know, by dragging the mouse or holding shift and using the arrow buttons), so it is not applicable to a select box, which has no selectable text. It works on certain input elements (like text) and textareas, or you can use it on the window.

onchange fires when the value of a form element changes - so this is what you need.

Note: using inline event handlers in your HTML is not a good idea most of the time. If you can, use addEventListener instead.

Community
  • 1
  • 1
kapa
  • 77,694
  • 21
  • 158
  • 175