I am using a combination of JQuery, Modernizr, and Angular to achieve a custom Datepicker solution for a table generated via ng-repeat. The solution works if I hard-code the Angular directive of "datepicker" into the HTML.
So, for example, within my table using ng-repeat"revenue in runway.revenues"
this works:
<td>
<input type="date" class="form-control" ng-model="revenue.date" placeholder="YYYY-MM-DD" datepicker required/>
</td>
But I would like for this to only be put into place when the user is in a browser that requires it. So, with this in mind, I have deleted datepicker
from the above HTML, and written this in JS:
$(function() {
var nativeDateInputIsSupported = Modernizr.inputtypes.date;
if (!nativeDateInputIsSupported) {
$('input[type="date"]').prop("datepicker", true)
}
});
However, when I land on the page in Firefox, it does not appear to work.
Further, if I try to debug by doing something like console.log($('input[type="date"]').prop("class"))
the value returned will be undefined
(which should be form-control
).
Any tips would be greatly appreciated!
Use .attr()
or .setAttribute()
to set attribute at HTML
document.querySelector("input").setAttribute("datepicker", true); console.log(document.querySelector("input").outerHTML);
<input type="text">
$("input").attr("datepicker", true); console.log($("input")[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <input type="text">
$("input").prop("datepicker", true); console.log($("input")[0].outerHTML); // attribute not set at HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <input type="text">
I was able to get this to work by taking an idea from user @guest271314 and expanding on it a bit!
Rather than adding the attribute to the HTML based on Modernizr, I set a $scope variable equal to a boolean value.
$(function() {
var nativeDateInputIsSupported = Modernizr.inputtypes.date;
if (!nativeDateInputIsSupported) {
$scope.datePickerValue = "true"
}
});
Within my directive, I added this:
function link(scope, element, attrs, controller) {
var requiredParam = attrs.datepicker === 'true'; //This was what was added
if (requiredParam) { //Checking for boolean value
element.datepicker({
dateFormat: "yy-mm-dd",
maxDate: '0'
});
}
}
Which meant that in my HTML I added datepicker="{{datePickerValue}}"
to the Date inputs, which now works!! Thank you for all of the help, I wouldn't have come back to this without your input =)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.