Reputation: 870
I'm using ASP.NET MVC 4 and jQuery to achieve this.
What I'm trying to do is to disable or enable a dropdownlist based on if a checkbox is checked or not.
I can get this working, however I can't seem to disable the dropdownlist on pageload. the statement is executed, but the element is not disabled.
What I think the problem is, is that the check is performed, BEFORE the dropdownlist (from the viewmodel) is populated, and the data somehow overrides?
Here's my HTML:
<p>
@Html.CheckBoxFor(model => model.RoomRequired, new { id= "room-required" })
<label>Room Required</label>
</p>
<p>
<label>Room Options</label>
@Html.DropDownListFor(model => model.OptionId, new SelectList(Model.RoomOptions, "Id", "Name"), "Select option", new { id="option-select })
</p>
and fixed Javascript:
$(document).ready(function () {
$('#room-required').change(function () {
$('#option-select').prop('disabled', $(this).is(':checked'));
});
$('#room-required').trigger('change');
});
Upvotes: 2
Views: 3629
Reputation: 870
I sorta of solved the problem. For some reason, jQuery was re-enabling the dropdownlist. I had to add a javascript script to the HTML page itself and trigger the change event in there. I know it's not the best solution, but it's a workaround that works for me.
Upvotes: 1
Reputation: 64526
.prop()
is preferred for changing the disabled
property, and you can pass it a boolean, so your code could be simplified to:
$('#option-select').prop('disabled', $('#room-required').is(':checked'));
Or full code:
$(document).ready(function () {
$('#room-required').change(function () {
$('#option-select').prop('disabled', $(this).is(':checked'));
});
$('#room-required').trigger('change');
});
Upvotes: 3
Reputation: 3283
What attr()
does is assigns the value in the second parameter to the specified attribute of the HTML element. We want <input disabled="disabled" />
and not <input disabled="true" />
.
So, use -
$('#option-select').attr('disabled', 'disabled');
instead of -
$('#option-select').attr('disabled', 'true');
Upvotes: 0