Adam R. Grey Adam R. Grey - 3 years ago 117
Javascript Question

Why does .prop("type") return "text" on a datetime input?

Given the very simple code:

<html>
<body>
<input type="datetime" id="TheInput"/>
<script type="text/javascript" src="./jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
alert($("#TheInput").prop("type"));
});
</script>
</body>
</html>


You'd think the messagebox would say "datetime", wouldn't it? But apparently it doesn't, it says "text". How and why is jQuery deciding to ignore what I wrote for the type? Shouldn't I be able to write any arbitrary type for the "type" property and see it messaged back to me? Is there a list of what jQuery thinks certain types should be?

(and as an aside, don't attempt to put this into jsFiddle or codepen. Both of those for some reason refuse to run my javascript. I don't know if I'm not allowed to use "prop" or if I'm not allowed to search by id, or what.)

Answer Source

Inputs of type datetime aren't supported anymore.

The browser replaces them with inputs of type text. That's why the type property of the input is "text".

A solution is to use inputs of type datetime-local.

console.log("type a : " + document.getElementById("a").type);
console.log("type b : " + document.getElementById("b").type);
<input id=a type=datetime>

<input id=b type=datetime-local>

Of course you could also read the attribute value (using attr with jQuery) but it would hide the real input's type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download