HPWD HPWD - 7 months ago 14
Javascript Question

name attribute missing when adding new element to dom (dynamically) using jQuery

I have this JavaScript function (below) that will dynamically add a new element to the DOM (no problem) except there is no name attribute added or ID value.

The ultimate goal I'm looking to achieve is to be able to dynamically add elements to a process and then be able to save it (submit via jQuery serialize) without a page refresh (in simple terms, think of adding/removing tasks to a project). Dynamically "adding" is what I'm struggling with.

Here is the stripped down code I have so far:

<div id="itemList">
<div><input class="textInput" name="input_1" id="input_1" type="text" /></div>
<div><input class="textInput" name="input_2" id="input_2" type="text" /></div>
<div><input class="textInput" name="input_3" id="input_3" type="text" /></div>
</div>
<div><a href="javascript:void('');" id="addNewInputField" onClick="addNewInputField();">Add New Task</a></div>

<script type="text/javascript">
function addNewInputField(){
elParentContainer = document.getElementById('itemList');
newElement = document.createElement('div');
newInput = document.createElement('input');
newInput.setAttribute('class', 'textInput');
newInput.setAttribute('type', 'text');
newElement.appendChild(newInput);
elParentContainer.appendChild(newElement);
}
</script>


and here is the outputted source I'm currently getting when clicking the "Add New Task" twice:

Here is the what I'm currently getting when you view source:

<div id="itemList">
<div><input class="textInput" name="input_1" id="input_1" type="text"></div>
<div><input class="textInput" name="input_2" id="input_2" type="text"></div>
<div><input class="textInput" name="input_3" id="input_3" type="text"></div>
<div><input class="textInput" type="text"></div>
<div><input class="textInput" type="text"></div>
</div>


Here is the desired output when you view source:

<div id="itemList">
<div><input class="textInput" name="input_1" id="input_1" type="text"></div>
<div><input class="textInput" name="input_2" id="input_2" type="text"></div>
<div><input class="textInput" name="input_3" id="input_3" type="text"></div>
<div><input class="textInput" name="input_4" id="input_4" type="text"></div>
<div><input class="textInput" name="input_5" id="input_5" type="text"></div>
</div>


Can someone help me modify my function to increment the newly added DOM elements?

Answer

If you want to use jQuery please consider using code like this:

  var inputCount = $('.textInput').size();
  inputCount += 1;
  $('#itemList').append('<div><input class="textInput" name="input_'+inputCount+'" id="input_'+inputCount+'" type="text" /></div>');

Additionally it may be more appropiate to use the data attribute, you might consider it.