繁体   English   中英

如何通过单击单选按钮使用javascript动态添加html中的文本字段

[英]How to add text field in html dynamically using javascript by clicking radio button

在html页面中,我需要两个单选按钮,以便在选择其中任何一个时,应将一个文本框自动添加到文档中。 如何使用javascript中的onclick事件获得这种效果?

$("#radioButtonId").click(function(){
   var ctrl = $('<input/>').attr({ type: 'text', name:'text', value:'text'});
   $("#containerId").append(ctrl);
});

编辑 :这是在JavaScript中使用jQuery。 要获取jQuery,请点击此处

在onclick事件上,调用函数并在其中传递this对象。 在函数中,检查this.id或this.class或this.name,以确保它是要在其上添加文本框的单选按钮。

在函数中写

var txt = document.createElement('input');
element.setAttribute("type", 'text');
element.setAttribute("name", 'name');
//select element in which you want to append textbox
var foo = document.getElementById("fooBar")
foo.appendChild(element);

如果您不必支持较旧的浏览器,并且可以插入已经隐藏在页面中的输入文本,那么我建议您使用另一种纯简单的CSS方法,请参见http://jsfiddle.net/wfwye/2/

<fieldset>
    <input type="radio" name="myradio" /><br>
    <input type="radio" name="myradio" /><br>
    ...
    <input type="text" />
</fieldset>

和CSS

[type="radio"] ~ [type="text"] { visibility: hidden; }
[type="radio"]:checked ~ [type="text"] { visibility: visible; }

我在这里使用了通用的同级选择器(MDN) (~)
不幸的是:checked IE <9不支持:checked伪类。

否则,“常规” JavaScript解决方案非常简单:假设您有

<fieldset>
    <input type="radio" name="myradio" /><br>
    <input type="radio" name="myradio" /><br>
</fieldset>

使用jQuery 1.7+,任务可以通过这种方式完成

$('input').on('click.appendInput', function() {
   $('<input type="text">').appendTo($(this).parent());
   $('input').unbind('click.appendInput');
});

unbind()是应有的,否则每次您单击单选输入时,都会添加一个新的输入文本(我认为这不是您想要的)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM