Naresh
Naresh

Reputation: 2781

clicked on radio button one time but input box is generating more than 1

i am generating a dynamic Input box with radio button selection. I am doing but problem is there.

Using a Select box i am generating a Radio button html and then from radio button, I am trying to generate only one input box on selection of every last radio button.

Problem: when i have clicked on radio button one time then Why input box is generating more than 1.

jsfiddle : http://jsfiddle.net/4A4FY/

enter image description here.

Jquery

  $("input[data-target='generateInput']").on('click', function (e) {
        var targetId = $(this).parent("div").attr("id");
        var t = $("div#input_" + targetId).append("<input type='text' name='aa' />");
    });

HTML

    <select id="e1" name='selectTag' multiple>
     <option value="ABC" data-id='1' id='1'>ABC</option>
     <option value="DEF" data-id='2' id='2'>DEF</option>
     <option value="GHI" data-id='3' id='3'>GHI</option>
     <option value="JKL" data-id='4' id='4'>JKL</option>
     <option value="MNO" data-id='5' id='5'>MNO</option>
   </select>
   <div id='generate' style='margin:10px;'></div> 

Upvotes: 0

Views: 126

Answers (2)

Shaunak D
Shaunak D

Reputation: 20636

Demo

Use .one('click..') - (reference) to add it only once.

$("input[data-target='generateInput']").one('click', function(e) {
    var targetId= $(this).parent("div").attr("id");
    console.log("#input_"+targetId);
    var t = $("div#input_"+targetId).append("<input type='text' name='aa' />"); 
});

Side Note: If you click twice on an <option> it is generating duplicate IDs

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

It is an expected behavior, Because you are appending the elements into the target element,

Try to use .html() at this context to accomplish your task..

$("input[data-target='generateInput']").on('click', function (e) {
    var targetId = $(this).parent("div").attr("id");
    var t = $("div#input_" + targetId).html("<input type='text' name='aa' />");
});

DEMO

Or write a condition to block the code flow if input has been appended already,

$("input[data-target='generateInput']").on('click', function (e) {
    var targetId = $(this).parent("div").attr("id");
    var elem = $("div#input_" + targetId);
    if(elem.find('input[name=aa]').length) { return; }
    var t = elem.append("<input type='text' name='aa' />");
});

DEMO

Upvotes: 2

Related Questions