Reputation: 15787
Say I have some JavaScript code which looks like this:
function CheckDateField()
{
if (!Modernizr.inputtypes.date) {
$(function () {
$(".datefield").datepicker();
});
}
}
This checks if the version of the browser is HTML 5 compliant and uses a date field if so; else a text field.
My .NET Core view has a field like this:
<div class="form-group">
<label asp-for="DOB" class="control-label"></label>
@*@Html.TextBox("datepicker")*@
@Html.TextBox("datepicker", null, new { @readonly = "readonly" })
How do I use the field in the JavaScript? I have tried this:
<label asp-for="DOB" class="control-label" onload="CheckDateField()"></label>
It would be good to put the JavaScript directly in the lavel if possible. I have spent two hours Googling this and have tried a few things, which have not worked.
Upvotes: 2
Views: 56
Reputation: 9348
You can simplify your code by just checking for the HTML5 input date
feature when the page is loaded and acting accordingly.
Also, the selector you're using to grab the element won't work, as the input
doesn't have a class datefield
set.
Your generated markup would look similar to this:
<label for="dob">Date of birth</label>
<input type="date" name="dob" id="dob" class="datefield">
Note the lack of the onload
event handler and that you set the input type
to date
to start with.
Your script bit to handle the datepicker
should be similar to this:
// When the document is ready.
$(function () {
// If input type date isn't supported.
if (!Modernizr.inputtypes.date) {
var el = $(".datefield");
// In a single call (chained) set the input type to text
// and attach the datepicker.
el.prop("type", "text").datepicker();
}
});
Upvotes: 3