In a html page I want two radio buttons so that when I select any of them a text box should be automatically added to the document. How to obtain this effect using the onclick event in JavaScript?
3 Answers
on the onclick event call a function and pass this object in it. In the function check this.id or this.class or this.name to make sure it is the radio button on which you want to add text box.
in the function write
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);
1 Comment
if you don't have to support older browser and you can insert your input text already hidden in your page, then I suggest an alternative pure simple CSS approach, see http://jsfiddle.net/wfwye/2/
<fieldset>
<input type="radio" name="myradio" /><br>
<input type="radio" name="myradio" /><br>
...
<input type="text" />
</fieldset>
and css
[type="radio"] ~ [type="text"] { visibility: hidden; }
[type="radio"]:checked ~ [type="text"] { visibility: visible; }
I used here the general sibling selector (MDN) (~).
Unfortunately :checked pseudoclass is not supported by IE<9
Otherwise the «regular» javascript solution is quite simple: assuming you have
<fieldset>
<input type="radio" name="myradio" /><br>
<input type="radio" name="myradio" /><br>
</fieldset>
using jQuery 1.7+ the task could be done in this way
$('input').on('click.appendInput', function() {
$('<input type="text">').appendTo($(this).parent());
$('input').unbind('click.appendInput');
});
The unbind() is due otherwise every time you click on a radio input you will append a new input text (I don't think it's what you want)