A
A
Adiost2011-08-18 22:52:26
JavaScript
Adiost, 2011-08-18 22:52:26

Dynamically adding fields to a form?

Good evening.

There was a need to organize a script for editing values ​​in the database.

Situation: there are three input fields in the form (for clarity, I will mention that they are located on one line), the name attribute for each input has the form name[N].

It is necessary to use JS, jQuery or anything else to add the ability to add a new line with three inputs with a change in the name (name[N + 1]) attributes.

Sorry for such an amateurish question, but I just can’t figure out how to implement this.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
N
nixmale, 2011-08-18
@nixmale

<div id="parentId">
  <div>
    <nobr><input name="name[1]" type="text" style="width:300px;" />
    <select size="1" name="type[1]" style="width:150px;">
      <option value="text">Текстовое поле</option>
      <option value="int">Целое число</option>
      <option value="float">Число-цена</option>
    </select>
    <a style="color:red;" onclick="return deleteField(this)" href="#">[—]</a>
    <input name="url[1]" type="text" style="width:300px;" />
    <a style="color:green;" onclick="return addField()" href="#">[+]</a></nobr>
  </div>
</div>

<script>
var countOfFields = 1; // Текущее число полей
var curFieldNameId = 1; // Уникальное значение для атрибута name
var maxFieldLimit = 25; // Максимальное число возможных полей
function deleteField(a) {
  if (countOfFields > 1)
  {
 // Получаем доступ к ДИВу, содержащему поле
 var contDiv = a.parentNode;
 // Удаляем этот ДИВ из DOM-дерева
 contDiv.parentNode.removeChild(contDiv);
 // Уменьшаем значение текущего числа полей
 countOfFields--;
 }
 // Возвращаем false, чтобы не было перехода по сслыке
 return false;
}
function addField() {
 // Проверяем, не достигло ли число полей максимума
 if (countOfFields >= maxFieldLimit) {
 alert("Число полей достигло своего максимума = " + maxFieldLimit);
 return false;
 }
 // Увеличиваем текущее значение числа полей
 countOfFields++;
 // Увеличиваем ID
 curFieldNameId++;
 // Создаем элемент ДИВ
 var div = document.createElement("div");
 // Добавляем HTML-контент с пом. свойства innerHTML
 div.innerHTML = "<nobr><input name=\"name[" + curFieldNameId + "]\" type=\"text\" style=\"width:300px;\" /> <select size=\"1\" name=\"type[" + curFieldNameId + "]\" style=\"width:150px;\"><option value=\"text\">Текстовое поле</option><option value=\"int\">Целое число</option><option value=\"float\">Число-цена</option></select> <a style=\"color:red;\" onclick=\"return deleteField(this)\" href=\"#\">[—]</a> <input name=\"url[" + curFieldNameId + "]\" type=\"text\" style=\"width:300px;\" /> <a style=\"color:green;\" onclick=\"return addField()\" href=\"#\">[+]</a></nobr>";
 // Добавляем новый узел в конец списка полей
 document.getElementById("parentId").appendChild(div);
 // Возвращаем false, чтобы не было перехода по сслыке
 return false;
}
</script>

A
Anatoly, 2011-08-19
@taliban

The simplest option:
We make a template of the desired html but as a variable value

vartpl="
<div>\
    <input name='name[%%num%%]'>\
    <input name='name[%%num%%]'>\
    <input name='name[%%num%%]'>\
</div>\
";

When you click on the button to add a new line, simply replace in the variable %%num%% with the counter ++
var currentTpl = tpl.replace(/%%num%%/g, counter++)
and paste after the current fields

X
xaker1, 2011-08-18
@xaker1

If I understand correctly, then:

$("#add_new_fields").live('click', function(){
  var num = $("#last_fields").attr("num");
    $("#last_fields").before('<input type="text" name=name['+(parseInt(num)+1)+'] value=""> 
Возможно описание здесь.');
    $("#last_fields").attr("num", (parseInt(num)+1))
});

In HTML
<tr id="last_fields" num="4"></td>
...
тут код
...
<a id="add_new_fields" href="javascript:void(0);" >Добавить еще</a>

When you click on the last button, the line "Here_insert_line" will be added before. But this code is adapted for the table, I do not think it will be difficult to adapt it to your case.

T
try4tune, 2011-08-18
@try4tune

Store the value of N in a variable (by default, assign, say, 0). Then, each time you press the button for adding inputs, create elements (document.createElement) and increment N. It seems that everything is pretty simple.

I
ivandanylovskyy, 2014-06-21
@ivandanylovskyy

A lot of time has passed, but if the author is still here, then I ask you to answer why there are slashes in the code below in the code "\\" I need to substitute my fields in this script, I can’t understand the syntax in any way, and I’m reluctant to learn Java for one form. Thank you in advance for your response

div.innerHTML = "<nobr><input name=\"name[" + curFieldNameId + "]\" type=\"text\" style=\"width:300px;\" /> <select size=\"1\" name=\"type[" + curFieldNameId + "]\" style=\"width:150px;\"><option value=\"text\">Текстовое поле</option><option value=\"int\">Целое число</option><option value=\"float\">Число-цена</option></select> <a style=\"color:red;\" onclick=\"return deleteField(this)\" href=\"#\">[—]</a> <input name=\"url[" + curFieldNameId + "]\" type=\"text\" style=\"width:300px;\" /> <a style=\"color:green;\" onclick=\"return addField()\" href=\"#\">[+]</a></nobr>";

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question