add a new text field every time a button is pressed - javascript

i am trying to create a bit of javascript that will create a new text field every time a button is pressed, any help would be appreciated, it seems like the javascript doesn't want to run more than once
<!DOCTYPE html>
<html>
<head>
<title>Q&A Admin Panel</title>
</head>
<body>
<h1>Q&A Admin Panel</h1>
<form action="add_question.php" method="post">
Question Type: <input type="text" id="questionType" />
Question Name: <input type="text" id="questionName" />
Question Text: <input type="text" id="questionText" />
<select id="myList" onchange="selectType()">
<option>Yes or No</option>
<option>Multiple Choice</option>
<option>Multiple Select</option>
<option>Open Response</option>
</select>
<div id='buttons'> </div>
</form>
<script type="text/javascript">
function selectType()
{
var type=document.getElementById("myList");
if(type == "Multiple Choice" or type == "Multiple Select"){
// add answer = visible
}
}
</script>
<script type="text/javascript">
var answers = 0;
function addAnswer()
{
write = document.getElementById('buttons');
write.innerHTML = write.innerHMTL + "add answer: <input type=\"text\" id=\"answer" + answers + "\" <br>";
answers = answers + 1;
}
</script>
<button onclick="addAnswer(); return false;">add answer</button>
</body>
</html>

var answers = 0,
write = document.getElementById('buttons');
function addAnswer() {
write.innerHTML += 'Add answer: <input type="text" id="answer"' + answers + '/> <br />';
answers++;
}​

I faced the same problem in my college project. You can also accomplish your work as David suggested, but using innerHTML doesn't add elements to DOM and as a result, when you'll refresh the page, text fields will disappear. So for getting persistent text fields, you can use the code mentioned below:
var i = 0;
function addMore()
{
var x = document.getElementById('buttons');
var input1 = document.createElement("input");
input1.setAttribute("type","text");
input1.setAttribute("name","i" + i );
x.appendChild( input1 );
i++;
}
You can use firebug for debugging javascript things.
Thanks.

function addTextField(id){
var colors = new Array('#660000','#33ff00','#0066ff','#cc3399','#9966ff');
var container = document.getElementById(id);
var ulElement = document.createElement('ul');
container.appendChild(ulElement);
var hideLink = function(){
var firstElement = ulElement.firstChild.getElementsByTagName('a')[0];
firstElement.style.display = (ulElement.childNodes.length==1)?'none':'inline';
for(var i = 0 ; i <ulElement.childNodes.length; i++)
ulElement.childNodes[i].style.color = colors[i%5];
}
var addListElement = function(){
var liElement = document.createElement('li');
ulElement.appendChild(liElement);
var textElement = document.createElement('input');
textElement.setAttribute('type','text');
liElement.appendChild(textElement);
var deleteLink = document.createElement('a');
deleteLink.href = "#";
deleteLink.appendChild(document.createTextNode('delete'));
liElement.appendChild(deleteLink);
deleteLink.onclick = function(){
ulElement.removeChild(liElement);
hideLink();
}
hideLink();
}
addListElement();
var anchorElement = document.createElement('a');
anchorElement.href = "#";
anchorElement.appendChild(document.createTextNode('Add more'));
container.appendChild(anchorElement);
anchorElement.onclick = addListElement;
hideLink();
}
Here is the Demo
http://jsfiddle.net/mannejkumar/cjpS2/

Related

How to create a button to add URL links in the form

Does anyone know how to add like a link button into a form? For example, a user clicks a + button and they can add an URL. They can add another URL if they wish and remove any links if required. Would be good to have validation for links as well.
I know for validation of the URL I can use "Check if a JavaScript string is a URL", but will need something that will validate all links if multiple have been added.
The best way to explain what I am trying to do is by looking at "Can I insert a hyperlink in my form?" in the form builder.
I just want to add links, and I don't need to display text or anything like that.
Is this what are you looking for?
Your question is a bit unclear.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
let i = 0;
let ii = 0;
function isURL(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
function removeLink(id, iid) {
console.log(id);
console.log(iid);
$(id).remove();
$(iid).remove();
return false;
}
function addLink(id) {
var input = prompt("Enter the link", "https://www.example.com");
var valid = isURL(input);
console.log(valid);
if(valid) {
var element = '<br><a id="_' + i + '" href="' + input + '">Link</a>';
console.log(element);
$(id).append(element);
let d = "'#_" + i + "'";
let dd = "'#__" + ii + "'";
let elment = ' <button type="button" id="__' + ii + '" onclick="removeLink(' + d + ', ' + dd + ')">Remove it!</button>';
$(id).append(elment);
console.log(elment);
i = i + 1;
ii = ii + 1;
}
else {
alert("The URL that you have entred is wrong.");
}
return false;
}
</script>
</head>
<body>
<form id="_form" method="POST">
<button type="button" onclick="addLink('#_form')">Add link</button>
</form>
</body>
</html>
Try it here: https://codepen.io/marchmello/pen/ZEGjMyR?editors=1000
What about DOM - not using longer form, so using URL as link text too.
function addUrl(e) {
var f = e.form;
var a = document.createElement("A");
a.href = e.value; // link URL
a.textContent = e.value; // link text
f.appendChild(a);
var x = document.createElement("INPUT");
x.type = "button";
x.value = "X";
x.onclick = remove;
f.appendChild(x);
f.appendChild(document.createElement("BR"));
}
function remove() {
var el = this, // button
parent = el.parentNode, // a must for remove
a = el.previousElementSibling; // anchor
if(el.nextSibling.tagName == 'BR') parent.removeChild(el.nextSibling);
parent.removeChild(el);
parent.removeChild(a);
}
<form>
<input name="url" size="50">
<input type="button" value="Add" onclick="addUrl(this.form.url)"><br>
</form>

Adding an event listener to DOM elements pushed into an array

Apologies for the poorly-worded question. It's my first question here!
I am trying to make an application whereby one can log the scores of players from any game and see the results at the end of the game (see the code snippet below).
So far, I have managed to push players and their scores (initially empty arrays) into the main array and thereby presented these players in a list (see below):
HTML
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
JavaScript
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
This gives me a list with the players' names, inputs to enter scores and buttons to log the scores. So far, so good.
But...
I am just trying to get each button to work. As you can see above, I gave each submit button classes ("submitScoreBtn"). I'm at the stage where I want to make sure that my new buttons work. Here's my code so far:
var enterScore = document.querySelectorAll(".enterScore");
var submitScore = document.querySelectorAll(".submitScoreBtn");
for (var x = 0; x < submitScore.length; x++){
submitScore[x].addEventListener("click", () => {
alert("selected");
});
}
I initially was getting errors without adding a for loop. Now I don't get any errors, but I also don't get any alerts. I'm just not sure why these buttons do not work.
Please see the code snippet below.
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
var enterScore = document.querySelectorAll(".enterScore");
var submitScore = document.querySelectorAll(".submitScoreBtn");
for (var x = 0; x < submitScore.length; x++){
submitScore[x].addEventListener("click", () => {
alert("selected");
});
}
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
Being as you're dynamically creating the buttons, it might be easier to simply add the function to the button's onclick.
You can still access the event object from this click by sending it as a parameter, like:
<input type='submit' onclick='submitScoreClick(event)' class='submitScoreBtn'>
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' onclick='submitScoreClick(event)' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
var enterScore = document.querySelectorAll(".enterScore");
var submitScore = document.querySelectorAll(".submitScoreBtn");
function submitScoreClick (e) {
alert("selected");
};
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
At the point in time when this code is run:
for (var x = 0; x < players.length; x++){
submitScore[x].addEventListener("click", (event) => {
event.alert("selected");
});
}
players.length is equal to 0. So the code is essentially never executed.
remove the for loop and add this code
document.addEventListener('click', function (event) {
if ( event.target.classList.contains( 'submitScoreBtn' ) ) {
alert("selected");
}
}, false);
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push({
player: entered,
score: []
});
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i = 0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className = "each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
document.addEventListener('click', function(event) {
if (event.target.classList.contains('submitScoreBtn')) {
alert("selected");
}
}, false);
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
var enterScore = document.querySelectorAll(".enterScore");
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
The easiest solution is to use variables and createElement just like you do with toAdd. This way each created entry will remember its own inputs (local variables to the function), and you can use for example the score input variable in the click handler without confusion of which number input belongs to which entry.
I removed the class for the inputs because it's not needed to select them anymore, but you can still add some for styling for example. If you want to add classes to select them all, be sure to run querySelectorAll each time, so that added elements are actually selected.
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
var addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
var createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " ";
var enterScore = document.createElement("input");
enterScore.type = 'number';
enterScore.placeholder = 'enter score';
var submitScore = document.createElement("input");
submitScore.type = 'submit';
submitScore.addEventListener("click", () => {
alert("selected score: " + enterScore.value);
});
newLi.appendChild(enterScore);
newLi.appendChild(submitScore);
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>

How to create a remove/delete function button in javascript? Button that can delete an element

I have A Form in HTML. Here's my Code:
<div id="format">
<form id="myForm" onsubmit="myForm(event)">
<b>Name:</b></br>
<input type="text" name="name" id="name" required="required" ></input></br>
<b>Phone Number:</b></br>
<input type="phone" name="phone" id="phone" required="required" ></input></br>
<b>Birthday:</b></br>
<input type="date" name="bday" id="bday" required="required" ></input></br>
<b>Email:</b></br>
<input type="email" name="email" id="email" required="required" ></input></br>
<b>Password:</b></br>
<input type="password" name="pWord" id="pWord" required" ></input></br>
<button type="submit" name="submit" id="submit" value="Submit" onsubmit="myData()" >Submit</button>
</form>
<div id="sample"></div>
</div>
Here's my Javascript code. In this code, when I trigger the submitted button from html, it will display the info of the user and append a div for each submitted info of the users.
var data = [];
var i, item;
function myForm(event){
event.preventDefault();
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var bday = document.getElementById("bday").value;
var email = document.getElementById("email").value;
var pWord = document.getElementById("pWord").value;
var age = document.getElementById("bday").value;
var ageValue;
var Bdate = document.getElementById("bday").value;
var Bday = +new Date(Bdate);
ageValue = ~~ ((Date.now() - Bday) / (31557600000));
var theBday = document.getElementById("age");
theBday.innerHTML = ageValue;
var userObject = {
name: name,
phone: phone,
bday: bday,
email: email,
pWord: pWord,
ageValue: ageValue,
};
data.push(userObject);
document.getElementById("sample").innerHTML = ""; //Prevents duplicate
for (var i=0 ; i <data.length ; i++){
var theDiv ;
var container ;
var button;
theDiv = document.createElement( "div" );
button = document.createElement( "button");
button.setAttribute("id", "remove");
button.remove(sample);
theDiv.style = "background-color:pink; border-style:solid; margin:1%;";
for (item in data[i]) {
var x = item + ":" + data[i][item] + "</br>" ;
theDiv.innerHTML += item + ":" + data[i][item] + "</br>" ;
}
button.innerHTML += "Remove";
button.style = "background-color:maroon; color:white;";
container = document.getElementById( "sample" );
container.appendChild( theDiv );
theDiv.appendChild (button);
}
console.log(data);
}
I want to to create a button for each appended div. The button will have the function of removing the entire div where the button belong.
A reasonably simple algorithm to correctly remove objects from the list is to provide a data- attribute value on each remove botton that gives its original index in the data array. (The attribute name used below is data-index).
Then take the inline code that adds objects and turn it into three functions to
(re-)draw all objects held in the data array.
add a single object to data and redraw all objects.
remove an object from the data array (coded as a remove button onclick handler) and redraw all objects.
The code already redraws all object when adding a new object is added, so redrawing everything when removing an object keeps it on the same level of simplicity.
Example code for simplified form:
"use strict";
var data = [];
function myFormData(event){
// halper functions
function addData( userObject) {
data.push(userObject);
redrawList();
}
function removeData( event) {
var index = this.getAttribute("data-index");
data.splice( index,1);
redrawList();
}
function redrawList() {
var container = document.getElementById( "sample" );
container.innerHTML = ""; // reset list displayed on page
for (var index=0 ; index <data.length ; index++){
var theDiv = document.createElement( "div" );
var divHTML = "";
var button = document.createElement( "button");
var userObject = data[index];
for( var item in userObject) {
if( !userObject.hasOwnProperty( item)) {
continue; // ignore inherited properties
}
divHTML += item + ":" + userObject[item] + "</br>" ;
}
theDiv.innerHTML = divHTML;
theDiv.style = "background-color:pink; border-style:solid; margin:1%;";
button.type="button";
button.setAttribute("data-index", index);
button.innerHTML = "remove";
button.style = "background-color:maroon; color:white;";
button.onclick=removeData;
theDiv.appendChild (button);
container.appendChild( theDiv );
}
}
// handle form submit event to add an event
event.preventDefault();
// cut down form:
var name = document.getElementById("name").value;
var userObject = {
name: name
};
addData( userObject);
// console.log(data); // not used in code example
}
<div id="format">
<form id="myForm" onsubmit="myFormData(event);">
<b>Name:</b></br>
<input type="text" name="name" id="name" required="required" ></input></br>
<button type="submit" name="submit" id="submit" value="Submit"
onsubmit="myFormData(event)" >Submit</button>
</form>
<div id="sample">
</div>
</div>
Note the code uses getAttribute("data-index") in case target browser support for element.dataset is unknown or absent. Function names myForm and myData were changed to myFormData as I presume they are the same function.
Probable issue: the existing code comment that clearing the sample list prevents duplicates is wrong. In the example code, clicking the submit button multiple times adds the same user. You could add a test to check for duplicate email addresses when adding a user to the list, but such code is outside the scope of this question. You may also wish to consider resetting the form after adding data to the "sample" list.
check the fiddler, i have implemented with a single value 'name'.
var data = [];
var i, item;
function myForm(event){
event.preventDefault();
var name = document.getElementById("name").value;
var userObject = {
name: name
};
data.push(userObject);
document.getElementById("sample").innerHTML = ""; //Prevents duplicate
for (var i=0 ; i <data.length ; i++){
var theDiv ;
var container ;
var button;
var index;
theDiv = document.createElement( "div" );
button = document.createElement( "button");
index = document.createElement("input");
index.setAttribute('hidden', 'true');
button.setAttribute("id", "remove");
button.setAttribute("onclick", "removeItem(this)");
for (item in data[i]) {
var x = item + ":" + data[i][item] + "</br>" ;
theDiv.innerHTML += item + ":" + data[i][item] + "</br>" ;
index.value += i;
}
button.innerHTML += "Remove";
container = document.getElementById( "sample" );
container.appendChild( theDiv );
theDiv.appendChild (button);
theDiv.appendChild(index);
}
}
function removeItem(event){
let el = event;
let index = el.parentNode.lastElementChild.value;
el.parentElement.remove();
data.splice(index,1);
}
<div id="format">
<form id="myForm" onsubmit="myForm(event)">
<b>Name:</b>
<input type="text" name="name" id="name" required="required" >
<button type="submit" name="submit" id="submit" value="Submit" onsubmit="myData()" >Submit</button>
</form>
<div id="sample"></div>
</div>

Trying to print out a input text the number of times the user wrote in the secound input using a while loop

I have two input fields and a button. When the user clicks the button, I want it to display the text the user wrote in the first input the amount of times the user wrote in the second input.
I understand you have to use a while loop for this. What am I doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
while (inputOne < inputTwo) {
text += inputOne;
inputOne++;
}
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Since inputOne is a text, you cannot increment it (you can't do inputOne++), instead, use another variable, let's call it i, to control the while loop:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
var i=1; // to control the loop
while (i <= inputTwo) { // i goes from 1 to inputTwo
text += inputOne;
i++;
}
document.getElementById("showCode").innerHTML = text;
}
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
This is my solution
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
var count = 0;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
console.log("Text: "+text);
var inputOne = document.getElementById("txtBox").value;
console.log("Input One: "+inputOne);
var inputTwo = document.getElementById("numBox").value;
console.log("Input 2: "+inputTwo);
count=count+1;
console.log("Times: "+count);
document.getElementById("numBox").value = count;
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Instead of the while loop you can use a for loop like this:
for( let i = inputTwo; i>0; i--) {
text += inputOne;
}

Changing the name of filedset elements while cloning with javascript

I have a requirement in which I had to add a duplicate of the existing fieldset in a form. I'm able to achieve the cloning process successfully. But I'm not able to change the name and id of the filedset elements. It is the same as the first fieldset but I want it to be with a different name and id to differentiate it(even adding a number at the end would be fine). Below are my js and fieldset.
<div id="placeholder">
<div id="template">
<fieldset id="fieldset">
<legend id="legend">Professional development</legend>
<p>Item <input type ="text" size="25" name="prof_itemDYNID" id ="prof_item_id"/><br /></p>
<p>Duration <input type ="text" size="25" name="prof_durationDYNID" id="prof_duration_id" /><br /></p>
<p>Enlargement <label for="enlargement"></label><p></p>
<textarea name="textareaDYNID" cols="71" rows="5" id="prof_enlargement">
</textarea></p>
<p><input type="button" value="Add new item" id="add_prof" onclick="Add();" /></p>
</fieldset>
</div>
</div>
function Add() {
var oClone = document.getElementById("template").cloneNode(true);
document.getElementById("placeholder").appendChild(oClone);
}
Also, this is just a sample fieldset and it will be different as well. I heard that this can be done using regex but not sure how to do it. Please help.
Not sure this could be achieve using regex, but somewhat following code should work...
var copyNode = original.cloneNode(true);
copyNode.setAttribute("id", modify(original.getAttribute("id")));
document.body.appendChild(el);
Here comes the best(as per my assumption) answer to the above problem..
function addMe(a){
var original = a.parentNode;
while (original.nodeName.toLowerCase() != 'fieldset')
{
original = original.parentNode;
}
var duplicate = original.cloneNode(true);
var changeID= duplicate.id;
var counter = parseInt(changeID.charAt(changeID.length-1));
++counter;
var afterchangeID = changeID.substring(0,changeID.length-1);
var newID=afterchangeID + counter;
duplicate.id = newID;
var tagNames = ['label', 'input', 'select', 'textarea'];
for (var i in tagNames)
{
var nameChange = duplicate.getElementsByTagName(tagNames[i]);
for (var j = 0; j < nameChange.length; j++)
{if (nameChange[j].type != 'hidden'){
var elementName = nameChange[j].name;
var afterSplitName = elementName.substring(0,elementName.length-1);
nameChange[j].name = afterSplitName + counter;
var elementId = nameChange[j].id;
var afterSplitId = elementId.substring(0,elementId.length-1);
nameChange[j].id = afterSplitId + counter;
}
}
}
insertAfter(duplicate, original);
}
function insertAfter(newElement, targetElement)
{
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
{
parent.appendChild(newElement);
}
else
{
parent.insertBefore(newElement, targetElement.nextSibling);
}
}

Categories