从HTML表单获取输入的类型 [英] Get the type of a input from an HTML form

查看:100
本文介绍了从HTML表单获取输入的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索Javascript中HTML表单输入的类型,以供进一步使用.我不是在说HTML输入的 type 属性,而是说您通过 typeof JS运算符获得的变量的类型.

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>

在我的梦中,它显示:"100 number | true boolean"而不是"100 string | true string".您能帮我定义自定义函数吗?

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

推荐答案

输入元素的value属性始终存储为字符串,因此typeof总是返回字符串".您需要编写一个自定义函数,该函数查看该字符串的内容并相应地确定正确的类型.这样的事情就足够了,尽管我可能错过了一两个案例:

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演示

这篇关于从HTML表单获取输入的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆