Cloning a div and getting specific id's value in the div - javascript

I have a html that will allow me to add or remove numbers of rows(divs) and a button that allows me to read through that number of rows(divs)
so the rows is as follow
<div id="mainContent">
<div id="StaffRow" class="WorkItemRow row" display:none;">
<div id="selections">
<select class="form-control">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div>
Name
</div>
<div>
<input id="MemberName" type="text" value="">
</div>
<div>
Mail
</div>
<div>
<input type="text" id="Mail" value="">
</div>
</div>
I've managed to clone the row as such
$('#ButtonAddStaff').click(function (e) {
counters++;
$("#StaffRow").clone(true).attr('id', "#StaffRow" + staffCount).appendTo("#mainContent");
$(".WorkItemRow").last().css('display', '');
});
but now the problem is i cant seem to iterate over the staffrow created and get the datas.
I've tried getting the data as such but it returns me undefined
for (let i = (counters- 1) ; i >= 0; i--) {
if (counters!= 1)
var nameData= document.getElementById('StaffRow' + i).children("#MemberName").val();
nameData= document.getElementById('StaffRow' + i);
list.push(nameData);
}
any idea where i should be looking to accomplish what i wanted to?
so what i wanna do is iterate over the created staffrow that is created after pressing the button and getting the values of membername in each of the row

I think your problem is here:
.attr('id', "#StaffRow" + staffCount)
When you do that, you actually set an id with the sharp. The second parameter of this function is not a kind a selector. Then you do a document.getElementById without this sharp.
You should use:
.attr('id', "StaffRow" + staffCount)

Maybe the following will help a bit, please let me know if you need more help.
This code does not rely on id's but uses a user defined attribute called x-role to indicate what role this element has in your program.
document.querySelector('#ButtonAddStaff').addEventListener(
"click",
function (e) {
const newRow = document.querySelector("#StaffRow").cloneNode(true);
//remove the id, no 2 same id's should be the same in dom
newRow.removeAttribute("id");
//set the x-role attribute, could set it on the hidden first but
// have to use .slice(1) when getting all the rows in getAllStaffRows
newRow.setAttribute("x-role","staffrow");
//show the row
newRow.style.display="";
document.querySelector("#mainContent").append(newRow);
}
);
//keep going to parent until we reach document or until function passed in
// returns true
const getParentUntil = fn => el => {
if(el===document.body){
return false;
}
if(fn(el)){
return el;
}
//keep calling itself until we find the correct parent
// or until we reach document
return getParentUntil(fn)(el.parentElement);
}
//remove handler
document.getElementById("mainContent").addEventListener(
"click",
e=>{
if(e.target.getAttribute("x-role")==="remove"){
const staffRow = getParentUntil(x=>x.getAttribute("x-role")==="staffrow")(e.target);
if(staffRow){
staffRow.remove();
}
}
}
)
document.querySelector('#logdata').addEventListener(
"click",
function (e) {
console.log(
JSON.stringify(
getAllStaffRows(),
undefined,
2
)
)
}
);
const getAllStaffRows = () =>
//get all html elements that have x-role attribute of staffrow
Array.from(document.querySelectorAll(`[x-role='staffrow']`))
//map the row elements into objects that contain the input values
.map(
row=>({
//find the element with x-role attribute that has a membername value
name:row.querySelector(`[x-role='membername']`).value,
//do this for selections and mail as well
selection:row.querySelector(`[x-role='selections']`).value,
mail:row.querySelector(`[x-role='mail']`).value
})
);
<input type="button" value="add" id="ButtonAddStaff">
<input type="button" value="log values" id="logdata">
<div id="mainContent">
<div id="StaffRow" class="WorkItemRow row" style="display:none;">
<div>
<select class="form-control " x-role="selections">
<option value=" "></option>
<option value="1 ">1</option>
<option value="2 ">2</option>
<option value="3 ">3</option>
</select>
</div>
<div>
Name
</div>
<div>
<input x-role="membername" type="text " value=" ">
</div>
<div>
Mail
</div>
<div>
<input type="text " x-role="mail" value=" ">
</div>
<div>
<input type="button" x-role="remove" value="remove">
</div>

Related

How can I fix this JS to jQuery conversion? (re: checkbox and dropdown option selection)

For practice, I'm taking working JavaScript code and converting what I can to jQuery. I've gone through StackOverflow and the jQuery documentation and am not finding what I need. Here's my original/working JS snippet:
if (checkbox.checked) {
let prefixmenu = document.getElementById('prefix_menu');
let prefix = prefixmenu.options[prefixmenu.selectedIndex].text;
para.textContent = prefix + " " + output;
} else {
para.textContent = output;
}
Without overloading you with the rest of the code, the goal is to take two form inputs, and an optional prefix (selected from a dropdown menu if a checkbox is checked), and generate those with pre-fabricated text in a 'clickbait headline generator.'
I've searched through this site and the jQuery documentation and have found things I thought might work but haven't. I tried this but then nothing prints:
if $("#checkbox :checked")
I thought this solution would work based on my research:
if ($checkbox.checked) {
let $prefix = $("#prefixmenu option:selected").text();
$para.text($prefix + " " + output);
} else {
$para.text(output);
}
})
From that, I get the pre-fab text with the form inputs to print, but not the prefix. I'm not sure what I'm missing.
<fieldset>
<legend>Generator inputs</legend>
<input type="checkbox" id="checkbox" value="prefix-select" name="optional_prefix">
<label for="prefix">Select to include a prefix</label><br>
<label for="prefix_menu">Prefix Selection:</label>
<select id="prefix_menu">
<option value="1">BOOM!</option>
<option value="2">WOW!</option>
<option value="3">EPIC!</option>
</select>
<label for="yourname">Your name</label>
<input type="text" id="yourname">
<label for="othername">Another person's name</label>
<input type="text" id="othername">
<button type="button" id="genButton">Generate!</button>
</fieldset>
One issue is that you're selecting $("#prefixmenu"), but the element's ID is "prefix_menu" (with an underscore). Use $("#prefix_menu") to access that element.
Also, checked is a property of the DOM element. $('#checkbox') is a jQuery object, which doesn't have a checked property of its own. However, you can access the DOM properties of selected elements with jQuery's .prop() method:
$checkbox.prop('checked')
Or you can access the property of the first DOM element directly:
$checkbox[0].checked
Or you can test against the :checked CSS pseudo-class using jQuery's is() method:
$checkbox.is(':checked')
Here's a working demonstration:
let $checkbox = $('#checkbox');
let $prefixMenu = $("#prefix_menu");
let $genButton = $("#genButton");
$genButton.on('click', function() {
let output = 'output';
if ($checkbox.is(':checked')) {
let prefix = $("option:selected", $prefixMenu).text();
output = prefix + " " + output;
}
console.log(output);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<legend>Generator inputs</legend>
<input type="checkbox" id="checkbox" value="prefix-select" name="optional_prefix">
<label for="prefix">Select to include a prefix</label><br>
<label for="prefix_menu">Prefix Selection:</label>
<select id="prefix_menu">
<option value="1">BOOM!</option>
<option value="2">WOW!</option>
<option value="3">EPIC!</option>
</select>
<label for="yourname">Your name</label>
<input type="text" id="yourname">
<label for="othername">Another person's name</label>
<input type="text" id="othername">
<button type="button" id="genButton">Generate!</button>
</fieldset>
These examples from .prop() further help to visualize those concepts:
if ( elem.checked )
if ( $( elem ).prop( "checked" ) )
if ( $( elem ).is( ":checked" ) )
Edit
I might use ternary operators to define the values:
let $checkbox = $('#checkbox');
let $prefixMenu = $("#prefix_menu");
let $genButton = $("#genButton");
let output = 'Output';
$genButton.on('click', function() {
let prefix = $checkbox.is(':checked')
? $("option:selected", $prefixMenu).text()
: false;
let headline = prefix
? prefix + " " + output
: output;
console.log(headline);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<legend>Generator inputs</legend>
<input type="checkbox" id="checkbox" value="prefix-select" name="optional_prefix">
<label for="prefix">Select to include a prefix</label><br>
<label for="prefix_menu">Prefix Selection:</label>
<select id="prefix_menu">
<option value="1">BOOM!</option>
<option value="2">WOW!</option>
<option value="3">EPIC!</option>
</select>
<label for="yourname">Your name</label>
<input type="text" id="yourname">
<label for="othername">Another person's name</label>
<input type="text" id="othername">
<button type="button" id="genButton">Generate!</button>
</fieldset>

Showing Div Not Working On Select Using Javascript

I am trying to show the FILE DIV if the user selects the doctor value in the select statement. I know the if statement works because I also print the value in the console which works perfectly fine. I toggle my divs in the same exact manner in my other webpages so I'm not understanding what's going on with this one in particular.
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}
}
.hidden{
display : none;
}
<div>
<select id="accountType" name="type" class="form-control" onchange="viewFile()">
<option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
****************************************EDIT-WORKAROUND**********************
Since my code refused to work, I added a line of code with 'head' being the title and not a real value. Thanks to everyone who contributed. I took out the hidden class altogether but when I add it, it still doesn't work correctly.
function viewDocFile() {
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if (type === 'regular' || type === 'head') {
file.style.display = "none";
console.log(type);
} else {
file.style.display = "block";
console.log(type);
}
}
***************************FINAL-EDIT************************
Kept the original code, but added the CSS inline.
<div class="form-group col-md-6" id="doclicense" style="display:none;">
Works perfectly now.
Here is an example of how this code should be written (even if there are still horrors)
// declare them here and not in a function where they will be redone each time the function is called
const
file_IHM = document.querySelector('#doclicense')
,
type_IHM = document.querySelector('#accountType') // and not with .value ...!
;
type_IHM.onchange = function()
{
file_IHM.style.display = (this.value==='doctor')?"block":"none";
console.log('type_IHM.value', this.value );
}
#doclicense { display : none; }
<div>
<select id="accountType" name="type" class="form-control" > <!-- let the js in the js part -->
<option required>Account Type</option>
<option value="doctor" id="doctor" >Doctor</option>
<option value="regular" id="regular" >Regular Account</option>
</select>
</div>
<div class="file-class" id="doclicense"> <!-- do not use class="hidden... -->
<input type="file" name="license" />
<input type="submit" /> <!-- there is no form anywhere... why don't you use <button> ?? -->
</div>
If that what your code really looks like, did you add your js in a <script></script> tag?
Or do you want to toggle the hide and show of the div?
if so this answer may help
<select id="accountType" name="type" class="form-control" onchange="viewFile()"><option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
<script>
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}else{
file.style.display = "none";
console.log(type);
}
}
</script>

Is there a way to simplify this into only a few lines of jQuery

I am trying to display input values of a form into their corresponding div/p tags. So whenever a user starts typing into an input field, that value will be written in the input box as well as in a p tag else where on the page.
I have my jQuery looking at every individual form field and displaying that info to an assigned p tag. Is there a way to write this code so I do not have to create multiple lines of code for each form field?
Write now it is checking for if there is a change in the form, and then seeing if the field has a value and if so displaying the information in the p tag, if not it makes the p tag empty.
He is what I have working now.
$('#webform-client-form-1').on('change',function(e){
/* Distributor Name INPUT */
var distributorNameInput=$('#edit-submitted-distributor-name').val();
if( !$("#edit-submitted-distributor-name").val() ) {
$(".distributor-name p").html("");
} else {
$(".distributor-name p").html("<strong>Distributor Name</strong> <br/>" + distributorNameInput);
};
/* Year INPUT */
var YearInput=$('#edit-submitted-year').val();
if( !$("#edit-submitted-year").val() ) {
$(".year p").html("");
}else {
$(".year p").html("<strong>Year</strong> <br/>" + YearInput);
};
/* General Information INPUT */
var generalinfoInput=$('#edit-submitted-general-information').val();
if( !$("#edit-submitted-general-information").val() ) {
$(".general-info").html("");
}else{
$(".general-info").html("<h2>General Information</h2> <p>" + generalinfoInput + "</p>");
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<form enctype="multipart/form-data" action="/" method="post" id="webform-client-form-1" accept-charset="UTF-8">
<p>
<label>Distributor Name*</label>
<input type="text" id="edit-submitted-distributor-name" name="submitted[distributor_name]" value=" " size="60" maxlength="128" class="form-text required">
</p>
<p>
<label for="edit-submitted-year">Year*</label>
<select id="edit-submitted-year" name="submitted[year]" class="form-select">
<option value="2015" selected="selected">2015</option>
<option value="2016">2016</option>
</select>
</p>
</form>
<div class="preview" id="preview">
<div class="distInfo">
<div class="distributor-name">
<p><strong>Distributor Name</strong> <br>Text will go here</p>
</div>
<div class="year">
<p><strong>Year</strong> <br>2015</p>
</div>
</div>
</div>
Instead of using IDs you can use classes and data attributes to pass input target element:
$(document).ready(function() {
$(document).on('change input paste', '.input', function() {
$($(this).data('target')).text($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" data-target="#text-input" />
<select class="input" data-target="#select-input">
<option value=""></option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<hr/>
<div id="text-input"></div>
<div id="select-input"></div>
you probably meaning something like inline if
/* Distributor Name INPUT */
var distributorNameInput = $('#edit-submitted-distributor-name').val();
$(".distributor-name p").html( distributorNameInput ? "<strong>Distributor Name</strong> <br/>" + distributorNameInput : "");
/* Year INPUT */
var YearInput = $("#edit-submitted-general-information").val();
$(".year p").html( YearInput ? "<strong>Year</strong> <br/>" + YearInput: "");
/* General Information INPUT */
var generalinfoInput = $('#edit-submitted-general-information').val();
$(".general-info").html( generalinfoInput ? "<h2>General Information</h2> <p>" + generalinfoInput : "");
The syntax for an inline if is
condition ? true code: false code
You can create an array of objects and iterate over it. This is great if you are thinking on adding new elements, because you will only need to add them to the array.
$('#webform-client-form-1').on('change',function(e){
var elements=new Array(
{valueToCheck:'edit-submitted-distributor-name',className:'distributor-name', label: 'Distributor Name'},
{valueToCheck:'edit-submitted-year',className:'distributor-name', label: 'Distributor Name'},
{valueToCheck:'edit-submitted-distributor-name',className:'distributor-name', label: 'Distributor Name'},
);
//check'em
elements.forEach(function(element){
var myValue=$("#"+element.valueToCheck).val();
$("."+element.className+" p").html( myValue ? "<strong>"+element.label+"</strong> <br/>" + myValue: "");
});
}

Text input from jquery not working

Hi I have a script that appends a set of constant string to a textarea it works fine if I click the button first but as soon as I input text on the textarea, the button does not append the constant string on the textarea if clicked again
here is my code for the click event:
$("#apply").on("click",function() {
var orange = $("#agent_option").val(),
lock = $("#agent_disallowed").val();
$("#textareaFixed").html(orange + " " + lock );
});
and Here is my html form:
<label for="agent_option" class="control-label">User-Agent :</label></div>
<div class="col-md-6">
<select id="agent_option" class="form-control input-sm">
<option value="all">All</option>
<option value="banana">Banana</option>
<option value="apple">Apple</option>
<option value="melon">Melon</option>
<option value="lynx">Lynx</option>
<option value="liger">Liger</option>
</select>
</div>
<div class="row">
<div class="col-md-4">
<label for="ax_disallowed" class="control-label">Disallow :</label></div>
<div class="col-md-6">
<input class="form-control input-sm" id="ax_disallowed" type="text" value="<?=ax_default_disallow;?>">
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="apply" class="btn btn-default">Register Player</button>
</div>
This is my textarea:
<form method="post" class="form-login">
<div class="form-group">
<textarea name="new_config" class="form-control" id="textareaFixed" cols="60" rows="16"><?=file_get_contents($open); ?></textarea>
</div>
</form>
please help me I tried google it but found irrelevant results. you guys are my only hope now :(
Change .html(...) to .val(...)
$("#apply").on("click",function() {
var orange = $("#agent_option").val(),
lock = $("#ax_disallowed").val();
$("#textareaFixed").val(orange + " " + lock );
});
You need to use append() instead of html()
Please try $("#textareaFixed").append(orange + " " + lock ); if you want to add the new text after the previous one.
If you use html(), it replaces the old stuff with the new one.
There isn't any input named as "agent_disallowed", you need to use correct id.
$("#apply").on("click",function() {
var orange = $("#agent_option").val();
var lock = $("#ax_disallowed").val();
$("#textareaFixed").html(orange + " " + lock );
});

jquery clone form fields and increment id

I have a block of form elements which I would like to clone and increment their ID's using jQuery clone method. I have tried a number of examples but a lot of them only clone a single field.
My block is structured as such:
<div id="clonedInput1" class="clonedInput">
<div>
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
</div>
Obviously elements are lined up a lot better but you get the idea.
I would like to keep the id structure i.e. category1, subcategory1 etc as I use these to dynamically display select options based on the parent selection so if its possible to have each cloned block like category1/category2/category3 etc that would be great.
HTML
<div id="clonedInput1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
</div>
JavaScript - Jquery v1.7 and earlier
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
$("button.clone").live("click", function(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
});
cloneIndex++;
});
There is only one silly part :) .attr("id", "clonedInput" + $(".clonedInput").length) but it works ;)
JAvascript - JQuery recent (supporting .on())
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
working example here
Another option would be to use a recursive function:
// Accepts an element and a function
function childRecursive(element, func){
// Applies that function to the given element.
func(element);
var children = element.children();
if (children.length > 0) {
children.each(function (){
// Applies that function to all children recursively
childRecursive($(this), func);
});
}
}
Then you can make a function or three for setting the attributes and values of your yet-to-be-cloned form fields:
// Expects format to be xxx-#[-xxxx] (e.g. item-1 or item-1-name)
function getNewAttr(str, newNum){
// Split on -
var arr = str.split('-');
// Change the 1 to wherever the incremented value is in your id
arr[1] = newNum;
// Smash it back together and return
return arr.join('-');
}
// Written with Twitter Bootstrap form field structure in mind
// Checks for id, name, and for attributes.
function setCloneAttr(element, value){
// Check to see if the element has an id attribute
if (element.attr('id') !== undefined){
// If so, increment it
element.attr('id', getNewAttr(element.attr('id'),value));
} else { /*If for some reason you want to handle an else, here you go*/ }
// Do the same with name...
if(element.attr('name') !== undefined){
element.attr('name', getNewAttr(element.attr('name'),value));
} else {}
// And don't forget to show some love to your labels.
if (element.attr('for') !== undefined){
element.attr('for', getNewAttr(element.attr('for'),value));
} else {}
}
// Sets an element's value to ''
function clearCloneValues(element){
if (element.attr('value') !== undefined){
element.val('');
}
}
Then add some markup:
<div id="items">
<input type="hidden" id="itemCounter" name="itemCounter" value="0">
<div class="item">
<div class="control-group">
<label class="control-label" for="item-0-name">Item Name</label>
<div class="controls">
<input type="text" name="item-0-name" id="item-0-name" class="input-large">
</div>
</div><!-- .control-group-->
<div class="control-group">
<label for="item-0-description" class="control-label">Item Description</label>
<div class="controls">
<input type="text" name="item-0-description" id="item-0-description" class="input-large">
</div>
</div><!-- .control-group-->
</div><!-- .item -->
</div><!-- #items -->
<input type="button" value="Add Item" id="addItem">
And then all you need is some jQuery goodness to pull it all together:
$(document).ready(function(){
$('#addItem').click(function(){
//increment the value of our counter
$('#itemCounter').val(Number($('#allergyCounter').val()) + 1);
//clone the first .item element
var newItem = $('div.item').first().clone();
//recursively set our id, name, and for attributes properly
childRecursive(newItem,
// Remember, the recursive function expects to be able to pass in
// one parameter, the element.
function(e){
setCloneAttr(e, $('#itemCounter').val());
});
// Clear the values recursively
childRecursive(newItem,
function(e){
clearCloneValues(e);
}
);
// Finally, add the new div.item to the end
newItem.appendTo($('#items'));
});
});
Obviously, you don't necessarily need to use recursion to get everything if you know going in exactly what things you need to clone and change. However, these functions allow you to reuse them for any size of nested structure with as many fields as you want so long as they're all named with the right pattern.
There's a working jsFiddle here.
Clone the main element, strip the id number from it.
In the new element replace every instance of that id number in every element id you want incremented with the new id number.
Ok, here's a quicky code here.
Basically, this part is the most important:
(parseInt(/test(\d+)/.exec($(this).attr('id'))[1], 10)+1
It parses the current id (using RegEx to strip the number from the string) and increases it by 1. In your case instead of 'test', you should put 'clonedInput' and also not only increase the value of the main element id, but the three from the inside as well (category, subcategory and subsubcategory). This should be easy once you have the new id.
Hope this helps. :)
Add data attribute to the input to get the field name, increment the value with variable.
html :
<td>
<input type="text" data-origin="field" name="field" id="field" required="" >
<div role="button" onclick='InsertFormRow($(this).closest("tr"),"tableID","formID");' id="addrow"> + </div>
</td>
and put this javascript function
var rowNum = 1;
var InsertFormRow = function(row, ptable, form)
{
nextrow = $(row).clone(true).insertAfter(row).prev('#' + ptable + ' tbody>tr:last');
nextrow.attr("id", rowNum);
nextrow.find("input").each(function() {
this.name = $(this).data("origin") + "_" + rowNum;
this.id = $(this).data("origin") + "_" + rowNum;
});
rowNum++;
}

Categories