aswathy aswathy - 3 months ago 6
Javascript Question

how to create different data id for text box which is getting on click

i want add text-boxes on each click that work well but i need add id for each text-boxes which is added dynamical. i am struggling to give id for it below i give the code used for adding textbox on click



$(function() {
$('.plusicon').on('click', function() {
var textBox = '<input type="text" class="textbox"/>';
var a = $(this).attr("id");
$('#' + a + "box").append(textBox);
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" />//for clickbutton//
<div id="plusicondivbox" class="insidediv " style="margin-top:-53px;"></div>//div for adding txtbox//




Answer

Have a global-variable and increment it after every click-event

$(function() {
  var count = 0;
  $('.plusicon').on('click', function() {
    var textBox = '<input type="text" class="textbox"/>';
    var a = $(this).attr("id");
    $('#' + a + "box").append(textBox);
    $('#' + a + "box input:last").attr('id', 'id_' + count);
    ++count;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" />
<br/>
<div id="plusicondivbox" class="insidediv"></div>

Or assign inline attribute by concatenation:

$(function() {
  var count = 0;
  $('.plusicon').on('click', function() {
    var textBox = '<input type="text" id="id_' + count + '" class="textbox"/>';
    var a = $(this).attr("id");
    $('#' + a + "box").append(textBox);
    ++count;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" />
<br/>
<div id="plusicondivbox" class="insidediv"></div>