问题
I'm trying to retrieve the type of my HTML form input in Javascript for further use. I'm not speaking about the type attribute of HTML input but the type of variable you get with typeof JS operator.
I'm using the code below to test it :
<form oninput="test();" name="myform">
<input name="anumber" value="100">
<input name="aboolean" value="true">
</form>
<div id="message"></div>
<script type="text/javascript">
function test(){
anumber = document.myform.anumber.value;
aboolean = document.myform.aboolean.value;
document.getElementById("message").innerHTML = anumber + " " + typeof(anumber) + " | " + aboolean + " " + typeof(aboolean)
}
</script>
In my dream, this displays : "100 number | true boolean" and not "100 string | true string". Can you help me to define the custom function to make it ?
Thank for your help ! Nicolas
回答1:
The value property of an input element is always stored as a string, so typeof is always going to return "string". You'd need to write a custom function that looks at the contents of that string and determines the correct type accordingly. Something like this may suffice, though I've likely missed one or two cases:
function getInputType(value) {
if(value === "")
return "";
else if(value === "true" || value === "false")
return "boolean";
else if(!Number.isNaN(Number(value)))
return "number";
else
return typeof value;
}
jsFiddle demo
来源:https://stackoverflow.com/questions/19513041/get-the-type-of-a-input-from-an-html-form