Reputation: 21
I have an MVC3 Razor application which I'm trying to execute simple Javascript on a dropdown list change.
My view uses a custom helper which return the proper object depending on the data type (dropdown list for enumerated lists, radio buttons for binaries, etc.)
The following helper:
@Html.RecipeEditorFor(model => model.Coating_Mode)
which renders the following selectlist in html:
<div class="form-line">
<div class="editor-field">
<select id="Coating_Mode" name="Coating_Mode">
<option value="1">Adhesive</option>
<option selected="selected" value="2">SR</option>
<option value="3">Inspection</option>
</select>
</div>
</div>
I want to have a simple Javascript execute whenever the value of the select list is changed:
<script type="text/javascript">
$('#Coating_Mode').change(function () {
alert("hello");
});
</script>
I will gladly provide any other code as needed to help answer the problem...
Upvotes: 2
Views: 2494
Reputation: 5024
It sounds like your script is running before the DOM has finished loading - ie, the script is placed before your helper.
It's good practice to wrap any javascript events inside a document ready event. Then the script can be placed anywhere (although in the head or right before </body>
are most appropriate).
So, change your script to this and it should work:
<script type="text/javascript">
// This function won't fire until the DOM is completely loaded.
$(document).ready(function() {
$('#Coating_Mode').change(function () {
alert("hello");
});
});
</script>
Upvotes: 0
Reputation: 7646
Try changing the script to:
<script type="text/javascript">
$(function () {
$('#Coating_Mode').change(function () {
alert("hello");
});
});
</script>
Also, I would advise against using an id in the selector if you intend to use this in a html helper. Use a class selector instead in case more than one item requires it.
Upvotes: 1