1

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 3

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

EDIT: This is using jQuery in javascript. To get jQuery look here

Sign up to request clarification or add additional context in comments.

1 Comment

OP asking about in javascript
0

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

Or var txt = document.createElement('textarea'); But then do not add the type, text attribute or it wont work.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.