为html表单创建输入字段...但也为它添加“标签”? [英] creating input field for html form... but adding a 'label' for it as well?

查看:103
本文介绍了为html表单创建输入字段...但也为它添加“标签”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML表单。单击该按钮时,javascript函数会添加一个新字段。我正在尝试让该功能也为该字段添加标签。

I have an html form. When you click the button, a javascript function adds a new field. I'm trying to have the function also add a 'label' for the field as well.

我尝试过使用document.createElement(LABEL),但这不能让我更改innerHtml(或者我做错了.. ),也不添加结束

I've tried using document.createElement("LABEL"), but that doesn't let me change the innerHtml (or maybe I'm doing it wrong..), nor add a closing

这是我的代码。谢谢!



var instance = 2;

Here is my code. Thanks! var instance = 2;

        function newTextBox(element)
        {       
            instance++; 
            // Create new input field
            var newInput = document.createElement("INPUT");
            newInput.id = "text" + instance;
            newInput.name = "text" + instance;
            newInput.type = "text";
            instance++; 

            document.body.insertBefore(document.createElement("BR"), element);
            document.body.insertBefore(newInput, element);

        }
    </script>
</head>


<body>
    <LABEL for="text1">First name: </LABEL>
    <input id="text1" type="text" name="text1">
    <LABEL for="text2">Last name: </LABEL>
    <input id="text2" type="text" name="text2">



    <input type="button" id="btnAdd" value="New text box" onclick="newTextBox(this);" />
</body>

推荐答案

   function newTextBox(element)
            {               
                    instance++; 
                    // Create new input field
                    var newInput = document.createElement("INPUT");
                    newInput.id = "text" + instance;
                    newInput.name = "text" + instance;
                    newInput.type = "text";

                    var label = document.createElement("Label");

                    label.htmlFor = "text" + instance;
                    label.innerHTML="Hello";
                    instance++; 

                    document.body.insertBefore(document.createElement("BR"), element);
                    document.body.insertBefore(newInput,element);
                    document.body.insertBefore(label, newInput);

请注意用于标签的属性,对应于属性 htmlFor 用于javascript中的标签对象

Note that for attribute of the label tag, corresponds to the property htmlFor fo the label object in javascript

这篇关于为html表单创建输入字段...但也为它添加“标签”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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