I'm trying to create an interactive resume template using javascript and html and have managed to use cloneNode to duplicate work history blocks (see attached screenshot)
The problem(s) I am having is that clicking on the add list item button in the cloned/duplicated work history block at the bottom, creates a <li> item in the 1st/cloned element.
The objective is to be able to add or delete ````` list elements within a specific work history block and to also be able to add/remove entire work history sections. Currently it deletes from the top down, which is also an issue.
Thanks for any pointers in advance.
CODE
<!DOCTYPE html>
<html>
<body>
<div id="test">
<div id="node">
<div class="work_history">
<div class="row">
<strong>
<input type="text" name="company" value="ACME Company">
</strong>
</div>
<div class="row">
<input type="text" name="position" value="Cheese Taster">
</div>
<input type="text" name="start" value="1/2019">
<input type="text" name="end" value="2/2020">
<ul id="list">
<li>
<textarea id="task" name="task" rows="4" cols="50">Did some things. Tasted cheese.</textarea>
</li>
<button onclick="addTask()">Add List Item</button>
<button onclick="RemoveTask()">Delete List Item</button>
</ul>
<button onclick="addWork()">Add Work</button>
<button onclick="removeWork()">Remove Work</button>
</div>
</div>
</div>
<script>
function addWork() {
var div = document.getElementById("node");
var cln = div.cloneNode(true);
//cln.setAttribute( 'id', 'newId');
document.getElementById("test").appendChild(cln);
}
function removeWork(){
var last = document.getElementById("test");
// want to delete the last added work history not first
last.removeChild(last.childNodes[0]);
}
function addTask(){
var ul = document.getElementById("list");
var task = document.getElementById("task");
var li = document.createElement("li");
li.setAttribute('id',task.value);
li.appendChild(document.createTextNode(task.value));
ul.appendChild(li);
}
function removeTask(){
var ul = document.getElementById("list");
var task = document.getElementById("task");
var item = document.getElementById(task.value);
ul.removeChild(item);
}
</script>
</body>
</html>
You'd have to use e.currentTarget instead of document.getElementById, otherwise you're only referring to the first instance of it:
function addWork(e) {
const div = e.currentTarget.parentElement;
const cln = div.cloneNode(true);
document.getElementById("test").appendChild(cln);
}
function removeWork(e) {
const last = e.currentTarget.parentElement;
last.parentElement.removeChild(last);
}
function addTask(e) {
const ul = e.currentTarget.parentNode;
let task = ul.children[0].childNodes[1].value;
let li = document.createElement("li");
// Replace paragraph breaks
task = task.replace(/\r?\n|\r/g, " ");
li.innerText = task;
ul.appendChild(li);
}
function removeTask(e) {
const ul = e.currentTarget.parentNode;
ul.removeChild(ul.lastChild);
}
<!DOCTYPE html>
<html>
<body>
<div id="test">
<div id="node">
<div class="work_history">
<div class="row">
<strong>
<input type="text" name="company" value="ACME Company">
</strong>
</div>
<div class="row">
<input type="text" name="position" value="Cheese Taster">
</div>
<input type="text" name="start" value="1/2019">
<input type="text" name="end" value="2/2020">
<ul id="list">
<li>
<textarea name="task" rows="4" cols="50">Did some things. Tasted cheese.</textarea>
</li>
<button onclick="addTask(event)">Add List Item</button>
<button onclick="removeTask(event)">Delete List Item</button>
</ul>
<button onclick="addWork(event)">Add Work</button>
<button onclick="removeWork(event)">Remove Work</button>
</div>
</div>
</div>
</body>
</html>
This allows you to refer to the specific element where the click event occurred and add/remove any elements that are relative within the DOM.
As a side note, it's best practice to have unique id attributes, adding the same id to multiple elements goes against that.
var add_button = $(".add_form_field");
var wrapper = $(".container1");
var max_fields = 9;
var x = 1;
$(add_button).click(function (e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append(
` <div class="email">
<label for="">Year</label>
<input type="text" name="eduYear${x}">
<label for="">Title Name</label>
<input type="text" name="eduTitle${x}">
<label for="">Institution/School Name</label>
<input type="text" name="eduPlace${x}">
<label for="">Details</label>
<input type="text" name="eduNotes${x}"> <br>Delete<hr></div>`
); //add input box
}
});
$(wrapper).on("click", ".delete", function (e) {
e.preventDefault();
$(this).parent("div").remove();
x--;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<h2>Educations</h2>
<button type="button" class="add_form_field">Add Education
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div class="email">
<label for="">Year</label>
<input type="number" name="eduYear1">
<label for="">Title Name</label>
<input type="text" name="eduTitle1">
<label for="">Institution/School Name</label>
<input type="text" name="eduPlace1">
<label for="">Details</label>
<input type="text" name="eduNotes1">
</div>
you can try this to create dynamic form
Related
I'm looking to clone addDriverContent (working fine) and increment the numbers for the name attribute on name="description" to name="description2", name="description3" on the clones
Also if anyone know how to also clone the add button so it works as it should on the clones would be extra points :) Some fiddles would be awesome :)
<div id="addDriverContent" style="display:none;">
<div class="content">
<div class="row">
<div class="col-md-12">
<label for="description" class="form-label font-weight-bold">Item Description:</label>
<input type="text" class="form-control" id="description" name="description" placeholder="Enter the items description"/>
</div>
</div>
</div>
</div>
<button type="button" class="add_field_button" id="clone_button">Add another item</button>
<div id="clone_wrapper"></div>
<script type="text/javascript">
$(function($) {
var max_fields = 4;
// origin selector would select all the first div ancestors.
var $content = $("#addDriverContent > .content");
var $clone_wrapper = $("#clone_wrapper") ;
var $add_button = $(".add_field_button"); //Add button ID
$add_button.click(function(e) {
e.preventDefault();
var counter = 0;
// jquery object is array liked object. Length mean how many elements is selected.
if ( $clone_wrapper.children(".content").length < max_fields )
$content.clone().appendTo($clone_wrapper);
});
$clone_wrapper.on("click",".remove_field", function(e){
e.preventDefault();
// this would be more specific.
$(this).parent(".content").remove();
})
});
</script>
As I have no idea what you intend to do with it, I will provide you with my dirty solution for it:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="addDriverContent" style="display:none;">
<div class="content">
<div class="row">
<div class="col-md-12">
<label for="description" class="form-label font-weight-bold">Item Description:</label>
<input type="text" class="description form-control" id="description" name="description" placeholder="Enter the items description"/>
<input type="text" class="fname form-control" id="fname" name="fname"/>
Remove<button type="button" class="add_field_button" id="clone_button">Add another item</button>
</div>
</div>
</div>
</div>
<button type="button" class="add_field_button" id="clone_button">Add another item</button>
<div id="clone_wrapper"></div>
<script type="text/javascript">
$(function($) {
var max_fields = 4;
// origin selector would select all the first div ancestors.
var $content = $("#addDriverContent > .content");
var $clone_wrapper = $("#clone_wrapper") ;
var $add_button = $(".add_field_button"); //Add button ID
$(".add_field_button").click(function() {
//e.preventDefault();
//var counter = 0;
// jquery object is array liked object. Length mean how many elements is selected.
if ( $clone_wrapper.children(".content").length < max_fields ) {
$content.clone().appendTo($clone_wrapper);
//$add_button.clone().appendTo($clone_wrapper);// mine
$(".description").each(function(index) {
$( this ).attr('name', 'description'+index)
});
$(".fname").each(function(index) {
$( this ).attr('name', 'fname'+index)
});
}
});
$(document).on('click', "#clone_wrapper .add_field_button", function () {
$('#addDriverContent + .add_field_button').trigger('click');
})
$(document).on('click', ".remove_field", function () {
//e.preventDefault();
// this would be more specific.
$(this).closest(".content").remove();
});
});
</script>
I'm trying to make it so when you push a button you add a note to the page. When I push the button, the new note flashes. I'm trying to get it to stay.
When I use a regular bracket object the new note stays. I could just switch to using one, but I wanna know if it's possible to make it work with a "this" object before switching.
The button used to add the note is under the "Note Drop-down" button
var dummyNotes = [];
class NewNote {
constructor(id, title, details, date) {
this.id = id;
this.title = title;
this.details = details;
this.date = date;
this.titleFormat = function() {
return `<span class="titleSpan">
<input type="text" class="noteTitle inputControls" value="${this.title}" maxlength="50">
<label class="editLabel detailScript">0/50</label>
<label class="editLabel errorMessage">Character limit reached!</label>
<span class="noteButtons">
<button class="editTitle">Edit</button>
<button class="deleteNote">Delete</button>
</span>
<span class="noteInfo">
<label class="theDate">${this.date}</label>
<label class="theID">${this.id}</label>
</span>
</span>`;
}
this.detailsFormat = function() {
return `<span class="detailsSpan">
<details><summary>Click for Details</summary>
<textarea class="noteDetails inputControls" maxlength="100">${this.details}</textarea>
<label class="editLabel detailScript">0/100</label>
<label class="editLabel errorMessage">Character limit reached!</label>
<button class="editDetails">Edit</button>
</details>
</span>`;
}
}
}
let newNoteInput = document.getElementById("newNoteInput");
newNoteInput.addEventListener('submit', addANote);
function addANote(){
/*If this fails, just copy paste what's under, insert values */
const pushNote = new NewNote(generateID(), newNoteTitle.value, newNoteDetails.value, dateNote.toLocaleDateString());
dummyNotes.push(pushNote);
addNewNote(pushNote);
newNoteTitle.value = "";
newNoteDetails.value = "";
}
function addNewNote(pushNote) {
const theNewNote = document.createElement("div");
theNewNote.classList.add("newNote");
const theNewNoteForm = document.createElement("form");
theNewNoteForm.classList.add("noteForm");
theNewNote.appendChild(theNewNoteForm);
theNewNoteForm.innerHTML = pushNote.titleFormat() + pushNote.detailsFormat();
noteList.appendChild(theNewNote); /*APPEND CHILD to get every item on the list*/
}
function init() {
dummyNotes.forEach(addNewNote);
noteList.innerHTML = "";
}
init();
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="Notes.css">
<meta name="viewport" content="width=device-width" initial-scale="1.0">
<title>Notes</title>
</head>
<body>
<div id="container">
<div id="noteContainer">
<details id="buttonContainer">
<summary id="toggleContainer">Note Drop-Down</summary>
<span id="newNoteToggle">
<form id="newNoteInput">
<span>
<input type="text" id="newNoteTitle" class="inputControls" placeholder="Title" maxlength="50">
<label class="newLabel detailScript">0/50</label>
<label class="newLabel errorMessage">Character limit reached!</label>
</span>
<span>
<input type="textarea" id="newNoteDetails" class="inputControls" placeholder="Details" maxlength="100">
<label class="newLabel detailScript">0/100</label>
<label class="newLabel errorMessage">Character limit reached!</label>
</span>
<button id="addButton">Add New Note</button>
</form>
</span>
</details>
<div id="noteList">
<div class="newNote">
<form class="noteForm">
<span class="titleSpan">
<input type="text" class="noteTitle" value="Note Title">
<button class="editTitle">Edit</button>
<button class="deleteNote">Delete</button>
<label class="theDate">The Date</label>
<label class="theDate">ID</label>
</span>
<span class="detailsSpan">
<details><summary>Click for Details</summary>
<textarea class="noteDetails"></textarea>
<button class="editDetails">Edit</button>
<span id="wordCount"></span>
</details>
</span>
</form>
</div>
</div>
</div>
<div id="searchContainer">
<details id="searchForm">
<summary><h4>Search Notes</h4></summary>
<form>
<input id="searchDate" type="date" placeholder="Date">
<input id="searchTitle" type="text" placeholder="Title">
<button id ="searchButton">Search</button>
</form>
</details>
</div>
</div>
<script src="Notes.js"></script>
</body>
</html>
Yep, as I suspected, your form was definitely posting without preventing default.
Please review the code, I've commented everywhere I made changes.
//was getting errors for these variables not being defined.
var dummyNotes = [],
dateNote = new Date();
class NewNote {
constructor(id, title, details, date) {
this.id = id;
this.title = title;
this.details = details;
this.date = date;
this.titleFormat = function() {
return `<span class="titleSpan">
<input type="text" class="noteTitle inputControls" value="${this.title}" maxlength="50">
<label class="editLabel detailScript">0/50</label>
<label class="editLabel errorMessage">Character limit reached!</label>
<span class="noteButtons">
<button class="editTitle">Edit</button>
<button class="deleteNote">Delete</button>
</span>
<span class="noteInfo">
<label class="theDate">${this.date}</label>
<label class="theID">${this.id}</label>
</span>
</span>`;
}
this.detailsFormat = function() {
return `<span class="detailsSpan">
<details><summary>Click for Details</summary>
<textarea class="noteDetails inputControls" maxlength="100">${this.details}</textarea>
<label class="editLabel detailScript">0/100</label>
<label class="editLabel errorMessage">Character limit reached!</label>
<button class="editDetails">Edit</button>
</details>
</span>`;
}
}
}
let newNoteInput = document.getElementById("newNoteInput");
//changed this function to run an anonymous function, prevent default and then call addANote():
newNoteInput.addEventListener('submit', function(e) {
e.preventDefault();
addANote();
});
function addANote(){
/*If this fails, just copy paste what's under, insert values */
const pushNote = new NewNote(generateID(), newNoteTitle.value, newNoteDetails.value, dateNote.toLocaleDateString());
dummyNotes.push(pushNote);
addNewNote(pushNote);
newNoteTitle.value = "";
newNoteDetails.value = "";
return false;
}
function addNewNote(pushNote) {
const theNewNote = document.createElement("div");
theNewNote.classList.add("newNote");
const theNewNoteForm = document.createElement("form");
theNewNoteForm.classList.add("noteForm");
theNewNote.appendChild(theNewNoteForm);
theNewNoteForm.innerHTML = pushNote.titleFormat() + pushNote.detailsFormat();
noteList.appendChild(theNewNote); /*APPEND CHILD to get every item on the list*/
}
function init() {
dummyNotes.forEach(addNewNote);
noteList.innerHTML = "";
}
//was getting error due to this function not existing, so I threw this in here:
function generateID() {
return parseInt(Math.random() * 10000);
}
init();
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="Notes.css">
<meta name="viewport" content="width=device-width" initial-scale="1.0">
<title>Notes</title>
</head>
<body>
<div id="container">
<div id="noteContainer">
<details id="buttonContainer">
<summary id="toggleContainer">Note Drop-Down</summary>
<span id="newNoteToggle">
<form id="newNoteInput">
<span>
<input type="text" id="newNoteTitle" class="inputControls" placeholder="Title" maxlength="50">
<label class="newLabel detailScript">0/50</label>
<label class="newLabel errorMessage">Character limit reached!</label>
</span>
<span>
<input type="textarea" id="newNoteDetails" class="inputControls" placeholder="Details" maxlength="100">
<label class="newLabel detailScript">0/100</label>
<label class="newLabel errorMessage">Character limit reached!</label>
</span>
<button id="addButton">Add New Note</button>
</form>
</span>
</details>
<div id="noteList">
<div class="newNote">
<form class="noteForm">
<span class="titleSpan">
<input type="text" class="noteTitle" value="Note Title">
<button class="editTitle">Edit</button>
<button class="deleteNote">Delete</button>
<label class="theDate">The Date</label>
<label class="theDate">ID</label>
</span>
<span class="detailsSpan">
<details><summary>Click for Details</summary>
<textarea class="noteDetails"></textarea>
<button class="editDetails">Edit</button>
<span id="wordCount"></span>
</details>
</span>
</form>
</div>
</div>
</div>
<div id="searchContainer">
<details id="searchForm">
<summary><h4>Search Notes</h4></summary>
<form>
<input id="searchDate" type="date" placeholder="Date">
<input id="searchTitle" type="text" placeholder="Title">
<button id ="searchButton">Search</button>
</form>
</details>
</div>
</div>
<script src="Notes.js"></script>
</body>
</html>
All I had to do to make the remove button work was write init like this:
function init() {
noteList.innerHTML = "";
dummyNotes.forEach(addNewNote);
}
noteList.innerHTML just needed to be on top!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am creating a HTML form in which I need to create a 'add more' button so another field appears. Any help would be appreciated
This isn't possible in pure HTML, but it can easily be achieved using javascript!
Basic example
In the basic example, you have one input field. When you click the add field button an extra input gets added after the last inserted input.
$(document).on('click', '.add_field', function() {
$('<input type="text" class="input" name="field[]" value="">').insertAfter('.input:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="input" name="field[]" value="">
</form>
<button type="button" class="add_field">Add field</button>
Copy value
This example is almost the same as the example above with one difference. It copies the value of the previous input. This is done with help of the JQuery .val() method
$(document).on('click', '.add_field', function() {
let value = $('.input:last').val(); // gets the value of the previous input
$('<input type="text" class="input" name="field[]" value="' + value + '">').insertAfter('.input:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="input" name="field[]" value="">
</form>
<button type="button" class="add_field">Add field</button>
Input groups
You could also copy an entire input group with multiple input fields.
$(document).on('click', '.add_field', function() {
$('<div class="input-group"><input type="email" class="input" name="email[]" value="" placeholder="Your email"><input type="password" class="input" name="password[]" value="" placeholder="Your password"></div>').insertAfter('.input-group:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
.input-group {
border-bottom: 1px solid gray;
padding: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-group">
<input type="email" class="input" name="email[]" value="" placeholder="Your email">
<input type="password" class="input" name="password[]" value="" placeholder="Your password">
</div>
</form>
<button type="button" class="add_field">Add field</button>
If you need any more examples please leave a comment!
Please try instead,
$(".Addmore").click(function(e) {
e.preventDefault();
// make a separation line
$("#FormItems").append('<hr width="300px">');
// append the input field as your needs
$("#FormItems").append('<input name="user" type="text" placeholder="Username"><br>');
$("#FormItems").append('<input name="email" type="email" placeholder="Email Address">');
});
.formwrapper{
text-align:center;
}
input{
padding:3px;
margin-bottom:5px;
display:inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formwrapper">
<form>
<div id="FormItems">
<input name="user" type="text" placeholder="Username"><br>
<input name="email" type="email" placeholder="Email Address">
</div>
<input type="button" value="Add More" class="Addmore">
<input type="submit" value="Submit">
</form>
</div>
In a few lines of js and html you can get that :
<button class="add-input">Add one more input</button>
<form action="." method="GET">
<div class="inputs">
<input type="text" name="text[]">
</div>
<input type="submit" value="submit">
</form>
<script>
const addButton = document.querySelector('button.add-input')
const inputDiv = document.querySelector('form .inputs')
addButton.addEventListener('click', ()=>{ // button to add the inputs
let newInput = document.createElement('input')
newInput.name = 'text[]' // add the name of the input
newInput.type = 'text' // add the type of the input
// you can add other attributes before appeding the node into the html
inputDiv.appendChild(newInput)
})
</script>
and you will have this as a result (I used php to prompt the result)
you can add as many input you want/need.
Next step is just doing some css
I hope this is, what you mean
<form>
<input type="text">
<input type="submit" value="cta">
</form>
<button>Add More</button>
<script>
document.querySelector('button').addEventListener('click', () => {
let field = document.createElement('input');
// change field however you'd like
document.querySelector('form').insertBefore(field, document.querySelector('form:last-child'));
})
</script>
You cannot create this using HTML only, you will need javascript. You could use a frontend framework like react.js to make life easy.
For example in react, you could bind an onclick listener on the button and maintain an array of values as state. Use this array to map value to your input. Whenever user clicks the button, you can then simply push a defaultValue to the array and react will handle the rest.
Import React, { useState } from 'react';
const Page = ()=>{
const [ arr, setArr ] = useState([""]);
const handleAdd = ()=>{
setArr([...arr, ""]);
};
return <form>
{arr.map((elem, index)=><input
onChange={ //"implement logic to update value stored in array" }
value={elem}
key={index} /> )}
<button onClick={()=>handleAdd()}>Add</button>
</form>
}
Using Bootstrap and jquery
Only in html is not possible, you need some on click event to trigger the functionality that may change the html dom.
You can use vanilla javascript as well, here is example using jquery library.
It will dynamically add and remove the element
index.html
<!DOCTYPE html>
<html>
<head>
<title>YDNJSY</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<!-- <h1>Lets learn javascript</h1> -->
<div class="col-xs-12">
<div class="col-md-12">
<h3> Actions</h3>
<div id="field">
<div id="field0">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="action_id">Action Id</label>
<div class="col-md-5">
<input id="action_id" name="action_id" type="text" placeholder=""
class="form-control input-md">
</div>
</div>
<br><br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="action_name">Action Name</label>
<div class="col-md-5">
<input id="action_name" name="action_name" type="text" placeholder=""
class="form-control input-md">
</div>
</div>
<br><br>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="col-md-4">
<button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
</div>
</div>
<br><br>
</div>
</div>
</body>
<script src="./index.js"></script>
</html>
index.js
$(document).ready(function () {
var next = 0;
$("#add-more").click(function (e) {
e.preventDefault();
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--><div class="form-group"> <label class="col-md-4 control-label" for="action_id">Action Id</label> <div class="col-md-5"> <input id="action_id" name="action_id" type="text" placeholder="" class="form-control input-md"> </div></div><br><br> <!-- Text input--><div class="form-group"> <label class="col-md-4 control-label" for="action_name">Action Name</label> <div class="col-md-5"> <input id="action_name" name="action_name" type="text" placeholder="" class="form-control input-md"> </div></div><br><br></div>';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div id="field">';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + next).attr('data-source', $(addto).attr('data-source'));
$("#count").val(next);
$('.remove-me').click(function (e) {
e.preventDefault();
var fieldNum = this.id.charAt(this.id.length - 1);
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
});
});
I'm trying to create new fields like the first field in this form by clicking on an image, but the fields are spawning below the button to submit and I don't understand why. The behavior I'm looking for is for the new fields to spawn above the button.
Here's my code
<div id="title">
<h1>Monthly Run Operations Assessment</h1>
</div>
<div class="row">
<div class="col-20" id="row-one">
<label for="name">1. </label>
</div>
<div class="col-60">
<input type="text" id="op" name="op" placeholder="Insert operation here">
</div>
<div class="col-20" id="symbol">
<img src="file:///C:/Users/user/Downloads/plus-circle-solid.svg" id="add">
</div>
</div>
<div id="submit">
<input type="submit" value="Submit">
</div>
</div>
This is the function:
var element = document.getElementById("add");
element.onclick = function() {
console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.body.appendChild(clone);
}
appendChild, as its name suggests, always appends the new element -- that is, it adds it to the end. What you want is insertBefore:
document.body.insertBefore(clone, ele);
One way to handle this is to wrap your form in a container and append to it :
var element = document.getElementById("add");
element.onclick = function() {
// console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.querySelector('#container').appendChild(clone);
}
<div id="title">
<h1>Monthly Run Operations Assessment</h1>
</div>
<div id="container">
<div class="row">
<div class="col-20" id="row-one">
<label for="name">1. </label>
</div>
<div class="col-60">
<input type="text" id="op" name="op" placeholder="Insert operation here">
</div>
<div class="col-20" id="symbol">
<img src="file:///C:/Users/user/Downloads/plus-circle-solid.svg" id="add">
</div>
</div>
</div>
<div id="submit">
<input type="submit" value="Submit">
</div>
</div>
I combined the above answers to achieve the expected behavior.
var element = document.getElementById("add");
element.onclick = function() {
// console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.querySelector('#container').insertBefore(clone, ele);
}
I'm working on a multi stage form with the following enabling the next/previous button to transit the form submission from one stage to the other:
$("input[name='next']").click(function(){
var output = validate();
if(output) {
var current = $("#signup-step.active");
var next = current .next(); //Just use .next() here to get the nextSibling of this li
if(next.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+next.attr("id")+"-field").show();
$("input[name='back']").show();
$("input[name='finish']").hide();
$(".active").removeClass("active");
next.addClass("active");
/* if($(".active").attr("id") == $("#signup-step.li").last().attr("id")) {
$("input[name='next']").hide();
$("input[name='finish']").show();
} */
if ( next.is(':last-child') ) {
$("input[name='next']").hide();
$("input[name='finish']").show();
}
}
}
});
$("input[name='back']").click(function(){
var current = $(".active");
var prev = $(".active").prev("#signup-step.li");
if(prev.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+prev.attr("id")+"-field").show();
$("input[name='next']").show();
$("input[name='finish']").hide();
$(".active").removeClass("active");
prev.addClass("active");
/*if($(".active").attr("id") == $("#signup-step.li").first().attr("id")) {
$("input[name='back']").hide();
}
*/
if ( next.is(':last-child') ) {
$("input[name='back']").hide();
}
}
});
By #signup-step:li I'm trying to refer to the li elements in a specific UL element because there two other UL element on the page: 1) UL of main menu, 2) UL of sidebars. Now since the main menu's UL comes before the form itself, the next/back button activate the menu items of the main menu rather the form stages. So being able to specify the UL referred will resolve this.
Kindly advise on the the correct for mat for selecting #signup-step:li in the code above?
Here is the form:
<ul id="signup-step">
<li id="Initiate" class="active">Initiate</li>
<li id="Strive">Strive</li>
<li id="End">End</li>
</ul>
<form name="frmRegistration" id="signup-form" method="post" enctype="multipart/form-data" action="sendemail.php">
<div id="initiate-field">
<label>Name of Organization</label><span id="coyname-error" class="signup-error"></span>
<div><input type="text" name="coyname" id="coyname" class="demoInputBox"/></div>
<label>Certificate of Incorporation No.</label><span id="cacnum-error" class="signup-error"></span>
<div><input type="text" name="cacnum" id="cacnum" class="demoInputBox"/></div>
<label>Registered Office Address</label><span id="regofficeaddy-error" class="signup-error"></span>
<div>
<textarea cols="30" rows="4" name="regofficeaddy" id="regofficeaddy" class="demoInputBox" class = "max10"></textarea>
</div>
<label>Operations Address</label><span id="opsaddy-error" class="signup-error"></span>
<div>
<textarea cols="30" rows="4" name="opsaddy" id="opsaddy" class="demoInputBox" class = "max10"></textarea>
</div>
</div>
<div id="strive-field" style="display:none;">
<label>Location of workshop/facility if different from office address given in the Structure Section:</label><span id="facilityloc-error" class="signup-error"></span>
<div>
<textarea cols="60" rows="8" name="facilityloc" id="facilityloc" class="demoInputBox" class = "max10"></textarea>
</div>
<label>Size of facility (in sq meters):</label><span id="facilitysize-error" class="signup-error"></span>
<div><input type="text" name="facilitysize" id="facilitysize" class="demoInputBox"/></div>
<label>Does your organization own or hire equipment:</label>
<div>
<input type="radio" name="facilityownhire" id="facilityownhire" value="Own"> Own
<input type="radio" name="facilityownhire" id="facilityownhire" value="Hire"> Hire <span id="facilityownhire-error" class="signup-error"></span>
</div>
</div>
<div id="end-field" style="display:none;">
<label>Does your Organization have an HSE Manual?</label>
<div>
<input type="radio" name="hsemanual" id="hsemanual" value="Yes"> Yes
<input type="radio" name="hsemanual" id="hsemanual" value="No"> No <span id="hsemanual-error" class="signup-error"></span>
</div>
<div id="hseevidenceBOX">
<label>If yes, please attach evidence</label><span id="hseevidence-error" class="signup-error"></span>
<div>
<input type="file" name="vendorfile[]" id="hseevidence" class="demoInputBox" />
</div>
</div>
<label>Does your Organization have a Safety Policy?</label>
<div>
<input type="radio" name="orgsafepolicy" id="orgsafepolicy" value="Yes"> Yes
<input type="radio" name="orgsafepolicy" id="orgsafepolicy" value="No"> No <span id="orgsafepolicy-error" class="signup-error"></span>
</div>
</div>
<div>
<input class="btnAction" type="button" name="back" id="back" value="Back" style="display:none;">
<input class="btnAction" type="button" name="next" id="next" value="Next">
<input class="btnAction" type="submit" name="finish" id="finish" value="Send" style="display:none;">
</div>
</form>
Thanks everyone for responding. I solve the problem of conflict with the main menu of the page I change the .active class to .here in the UL HTML, CSS and jquery script. I also reliazed from this fiddle http://jsfiddle.net/GrahamWalters/sgNH4/2/ i gained from another thread that the next("#signup-step.li"); should be next("#signup-step li");
UL HTML
<ul id="signup-step">
<li id="Initiate" class="active">Initiate</li>
<li id="Strive">Strive</li>
<li id="End">End</li>
</ul>
CSS
#signup-step li.here{background-color:#FF0000;}
.here{color:#FFF;}
JQUERY
$("#next").click(function(){
var output = validate();
if(output) {
var current = $(".here");
var next = $(".here").next("#signup-step li");
if(next.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+next.attr("id")+"-field").show();
$("#back").show();
$("#finish").hide();
$(".here").removeClass("here");
next.addClass("here");
if($(".here").attr("id") == $("#signup-step li").last().attr("id")) {
$("#next").hide();
$("#finish").show();
}
}
}
});
$("#back").click(function(){
var current = $(".here");
var prev = $(".here").prev("#signup-step li");
if(prev.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+prev.attr("id")+"-field").show();
$("#next").show();
$("#finish").hide();
$(".here").removeClass("here");
prev.addClass("active");
if($(".here").attr("id") == $("li").first().attr("id")) {
$("#back").hide();
}
}
});