[英]How to change input type dynamically using jquery or javascript
Below is the my html code: 以下是我的html代码:
<input type="checkbox" id="multiOptions" />IsForMultioptions
<input type="radio" value="1" name="option">option1
<input type="radio" value="2" name="option">option2
If I select checkbox ie multiOptions then all radio buttons should be convert into checkboxes. 如果我选择复选框,即multiOptions,那么所有单选按钮都应转换为复选框。 and If I uncheck the checkbox ie multiOptions then all checkboxes should convert in radio buttons.
如果我取消选中复选框,即multiOptions,则所有复选框都应转换为单选按钮。 thanks in advance.
提前致谢。
You'll need to actually remove and recreate the elements, because IE doesn't let you change the type
of an input
after it's created. 您实际上需要删除并重新创建元素,因为IE不允许您在创建
input
后更改其type
。
jQuery makes this fairly easy with replaceWith
: jQuery通过
replaceWith
使这变得相当容易:
$("selector for the input to change").replaceWith('<input type="checkbox">');
So for instance: 因此,例如:
$('input[type="radio"][name="option"]').each(function() {
$(this).replaceWith('<input type="checkbox" name="option" value="' + this.value + '">');
});
Or if the values may contain characters requiring entities: 或者,如果值可能包含要求实体的字符:
$('input[type="radio"][name="option"]').each(function() {
var rep = $('<input type="checkbox" name="option">');
rep.attr("value", this.value);
$(this).replaceWith(rep);
});
Instead of replacing the elements you can have two groups of which one is hidden depending on the checkbox: 不用替换元素,可以有两组,根据复选框隐藏其中的一组:
HTML 的HTML
<input type="checkbox" id="multiOptions">IsForMultioptions</input>
<div id="radios">
<input type="radio" value="1" name="option">option1</input>
<input type="radio" value="2" name="option">option2</input>
</div>
<div id="checkboxes">
<input type="checkbox" value="1" name="option">option1</input>
<input type="checkbox" value="2" name="option">option2</input>
</div>
jQuery jQuery的
$(document).ready(function() {
$('#checkboxes').hide();
$('#multiOptions').on('click', function() {
if ($(this).is(':checked')) {
$('#radios').hide();
$('#checkboxes').show();
}
else {
$('#radios').show();
$('#checkboxes').hide();
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.