user2284341
user2284341

Reputation: 671

Trying to fire JQuery from 'onchange' in an Html.DropDownFor helper

What I am trying to do is set the selected value in dropdown 'b' from dropdown 'a' when the user selects different options from dropdown 'a'.

I'm using the html helper 'DropDownFor' for dropdown 'a' in an MVC project:

<%=Html.DropDownListFor(r => r.FrequencyId, frequencyItems, new {  onchange ="ddMonthChange" })%>

I want the 'onchange' event to call this JQuery code:

$(document).ready(function ddMonthChange () {
var frequency = document.getElementById("FrequencyId").options[document.getElementById("FrequencyId").selectedIndex].value;
alert("frequency is " + frequency);

});

I've a tag in the same view as dropdown 'a' that looks like this:

<script type="text/javascript" src="../../Scripts/jquery.setMonthly.js"></script>

So, clearly this is wrong. The script does run but only when the view is loaded (the alert pops up) and does nothing when I select a different item from dropdown 'a'.

How do I wire this up so that my script fires when a different item is selected?

thanks in advance,

Upvotes: 2

Views: 1223

Answers (2)

G&#246;khan Girgin
G&#246;khan Girgin

Reputation: 1164

just change it

$(document).on("change","select[name=FrequencyId]",function(){
     alert("frequency is " + $(this).val());
});

Upvotes: 1

Christoffer Mansfield
Christoffer Mansfield

Reputation: 803

You need to remove the jQuery ready part like so:

function ddMonthChange () {
    var frequency = document.getElementById("FrequencyId")
        .options[document.getElementById("FrequencyId").selectedIndex].value;
    alert("frequency is " + frequency);
}

This is because $(document).ready(...) simply runs the function you pass in (in your case ddMonthChange) when the DOM has finished loading. Since you want your function to be available in the Global scope, so that the drop down can call it whenever it changes, you cannot pass it in to jQuery's ready function

If you want to read more about scope in Javascript: http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

Upvotes: 0

Related Questions