Dynamically add button, textbox, input, radio elements in html form using JavaSc

文章源自:http://viralpatel.net/blogs/dynamic-add-textbox-input-button-radio-element-html-javascript/

Dynamically add button, textbox, input, radio elements in html form using JavaScript

Adding Elements like textbox, button, radio button etc in a html form using JavaScript is very simple. JavaScript’s document object has a method called createElement() which can be used to create html elements dynamically.

We had used this function in our tutorial: Dynamic combobox-listbox-drop-down using javascript to add dynamic options to a combo box-listbox. Let us use this function to create textboxes, radio buttons, buttons etc dynamically and add them in our page.

 

Following is the source code of our example.

<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function add(type) {
 
    //Create an input type dynamically.
    var element = document.createElement("input");
 
    //Assign different attributes to the element.
    element.setAttribute("type", type);
    element.setAttribute("value", type);
    element.setAttribute("name", type);
 
 
    var foo = document.getElementById("fooBar");
 
    //Append the element in page (in span).
    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" οnclick="add(document.forms[0].element.value)"/>
 
<span id="fooBar">&nbsp;</span>
 
</FORM>
</BODY>
</HTML>

 Also note that we have used setAttribute() method to assign the attributes to our dynamically created element.



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值