Reputation: 2070
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
{
@Scripts.Render("~/js/index-layout")
<script type="text/javascript">
function linkify()
{
jQuery.event.trigger('linkify');
}
(function() {
$(document)
.ready(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("_", " "))'));
}
$typeCell.append($typeField);
$('#PType').change(function (e)
{
if ($('#PType').val() == "Conditional_Locked")
{
alert("Hello");
$('#FType_chosen').removeClass('hidden');
$('#FTypeLabel').removeClass('hidden');
$('#PIds_chosen').removeClass('hidden');
$('#PIdsLabel').removeClass('hidden');
}
else
{
alert("Bye");
$('#FType_chosen').addClass('hidden');
$('#PIds_chosen').addClass('hidden');
$('#FTypeLabel').addClass('hidden');
$('#PIdsLabel').addClass('hidden');
}
});
$(document)
.bind('linkify',
function()
{
doLinkify($elements.$resultDetailView);
});
});
})();
</script>
}
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).
Upvotes: 1
Views: 161
Reputation: 4417
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:
$(document).on({
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.
Upvotes: 1