在动态创建的文本框上添加标签

时间:2015-02-28 09:16:19

标签: javascript php html

这里我有动态创建文本框和按钮的代码。问题是我想在这个文本框中添加我想要的标签而不是静态占位符值。请帮助我。这是代码。

<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html 
Form using    JavaScript</TITLE>
<SCRIPT language="javascript">
function add(type) {
var element = document.createElement("input");
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
var foo = document.getElementById("fooBar");
foo.appendChild(element);}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<SELECT name="element">
<OPTION value="button">Button</OPTION>
<OPTION value="text">Textbox</OPTION>
<OPTION value="radio">Radio</OPTION>
</SELECT>
<INPUT type="button" 
value="Add"    onClick="add(document.forms[0].element.value)"/>
<span id="fooBar">&nbsp;</span>
</FORM>

   

1 个答案:

答案 0 :(得分:0)

我认为你在寻找

 function add(type) {
    var foo = document.getElementById("fooBar");
    if(type=="text"){

        foo.innerHTML +="Text:<input type='text'>"
    }else{
        var element = document.createElement("input");
        element.setAttribute("type", type);
        element.setAttribute("value", type);
        element.setAttribute("name", type);
        foo.appendChild(element);
    }

}

FIDDLE

简化代码

function add(type,label) {

   var foo = document.getElementById("fooBar");

  foo.innerHTML +=""+label+":<input type='"+type+"' value="+label+">";

}

Fiddle