Get the type of a input from an HTML form

回眸只為那壹抹淺笑 提交于 2020-01-16 14:31:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!