Kala J Kala J - 1 month ago 7x
C# Question

onChange event does not get called

I have this change function that removes or adds the hidden class to a razor dropdownlist.
This checks if a value in one of the dropdowns is that string, then on change, either remove or add the class based on that selection.

<label class="control-label col-md-4 optional" id="PIdsLabel" for="pIds">PIds</label>
@Html.DropDownList("PIds", allPlacements, new { htmlAttributes = new { @multiple = true, @data_placeholder = "Select", @class = "form-control no-chosen hidden"}})

<label class="control-label col-md-4 optional" id="FLabel" for="FType">FType</label>
@Html.DropDownList("FType", Enum.GetValues(typeof(FType)).Cast<FType>().Select(o => new SelectListItem { Text = o.GetDescription(), Value = o.ToString()}), new { htmlAttributes = new { @multiple = true, @data_placeholder = "Select", @class = "form-control no-chosen hidden"}})

@section Scripts
<script type="text/javascript">

function linkify()

(function() {

var $typeCell = $('<td></td>');

var $typeField = $('<select></select>')
.attr('class', 'text-box single-line form-control')
.attr('id', 'PType')
.attr('name', 'PCs[0].PType');

@foreach (var item in allPTypes)
@:$typeField.append($('<option>').attr('value', "@item").text('@(((PType) item).ToString().Replace("_", " "))'));


$('#PType').change(function (e)

if ($('#PType').val() == "Conditional_Locked")


Problem is the change event is never fired. Why?

.hidden {
display: none;

I tried to run the snippet with the change event inside the browser console window and it works fine. I added the alerts to see if they fire and it runs fine when I run it straight from console window. Not when the page loads and the selection changes are not detected (unless I run into directly into console).


Your select is dynamic. When the self invoking function is ran and binding the change event takes place, it has nothing to bind to because the dom element isn't on the dom at that moment. What you need to do is this:

change: function (e, i) {
   //your code goes here
 }, '#Ptype');

What this is doing is telling the document to listen constantly for a change in an element called PType. You can put this code anywhere in your javascript. This will handle dynamic elements.