I have an MVC application with a simple control to all selection of All Dates or selecting a Date Range.
The radio buttons have an onclick handler to enable/disable the dat pickers. All work well so far.
When I try to set the correct context state for the datepickers after doing a POST I 开发者_Go百科cannot get the jQuery selector to return the radio buttons checked value.
The code is as follows:
<%= Html.RadioButton("DateSelection.AllDates", "AllDates", Model.AllDates == "AllDates", new { onclick = "setReadOnly(this);" })%>ALL Dates
<%= Html.RadioButton("DateSelection.AllDates", "Selection", Model.AllDates == "Selection", new { onclick = "setReadOnly(this);" })%>Selection
<%= Html.DatePicker("DateSelection.startdate", Model.StartDate, "", "") %>
To <%= Html.DatePicker("DateSelection.enddate", Model.EndDate, "", "") %><br />
The javascript is as follows:
<script type="text/jscript" >
function setReadOnly(obj) {
if (obj.value == "Selection") {
$('#DateSelection_startdate').css('backgroundColor', '#ffffff')
.removeAttr('readonly')
.datepicker('enable');
$('#DateSelection_enddate').css('backgroundColor', '#ffffff')
.removeAttr('readonly')
.datepicker('enable');
}
else {
$('#DateSelection_startdate').css('backgroundColor', '#eeeeee')
.attr('readonly', 'readonly')
.val('')
.datepicker('disable');
$('#DateSelection_enddate').css('backgroundColor', '#eeeeee')
.attr('readonly', 'readonly')
.val('')
.datepicker('disable');
}
}
<script type="text/jscript">
$(document).ready(function() {
$('#DateSelection_startdate').datepicker('disable').css('backgroundColor', '#eeeeee')
.attr('readonly', 'readonly')
.val('');
$('#DateSelection_enddate').datepicker('disable').css('backgroundColor', '#eeeeee')
.attr('readonly', 'readonly')
.val('');
var selected = $('#DateSelection_AllDates:checked');
setReadOnly(selected);
});
The javascript line that is causing the problem is
var selected = $('#DateSelection_AllDates:checked');
which will NOT return the checked radio button.
Using
var selected = $('#DateSelection_AllDates');
will return the first radio button value as expected i.e. applying the ':checked' filter ALWAYS returns undefined.
Can anyone see anything wrong here?
I think you need something more like this:
$("input[name='DateSelection_AllDates']:checked")
Hard to tell without seeing your generated HTML, since I don't know MVC. Clearly you have multiple radio buttons with the same NAME (hence a group, yes?). This is not the same as an ID, which by definition must be unique.
http://api.jquery.com/checked-selector/
精彩评论