Get specific h3 from multiple cloned divs - javascript

I'm trying to get a specific h3 from a cloned div when pressing a button. Since I got 10 cloned divs with the exact same values I want to be able to get the h3 from the specific button I just pressed.
$("body").on("click", ".btnFavorite", function() {
var favoriteMovieTest = $(this).parent().find("h3");
alert(favoriteMovieTest);
});
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>

You can do it like this:
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
}
$(".btnFavorite").on("click", function() {
var favoriteMovieTest = $(this).closest("div").find("h3");
favoriteMovieTest.css('color','red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>
As you can see i get that specific h3 element from the button.
Now you can do whatever you like with it, for example manipulate it's CSS code to change the color, like I did.

Try this.
Note : Keep code to attach event handler after for loop because if it is executed before for loop, elements created by for loop won't be attached with a event handler.
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search").find("h3").append(" "+i);
}
$(".btnFavorite").on("click", function() {
var favoriteMovieTest = $(this).siblings("h3")[0];
console.log(favoriteMovieTest);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>

You can climb up and down the DOM to get and title or index number of which cloned element was clicked.
$("body").on("click", ".search .btnFavorite", function(e) {
var elIndex = Array.from(e.target.parentNode.parentNode.children).indexOf(e.target.parentNode);
var favoriteMovieTest = e.target.parentNode.innerText;
alert('H3: ' + favoriteMovieTest + ' index: ' + elIndex);
});
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3 id='title'>Title(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>

Related

Making div tag invisible on page load and display several div tags on button click

I want to make a div tag invisible when the page loads and make it visible everytime a button is clicked. This is what I have on my page:
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>
Whenever AddItem button is clicked, I want to display one Div tag/item so if I click "Add Item" button, I want to make visible only div tag "realProp1", now if I click "AddItem" button again, I want to make visible "realProp2" div tag. Below is what I have, the code is working for one div tag, but not for several div tags:
<script>
window.onload = function () {
document.getElementById("realProp1").style.display = 'none';
document.getElementById("realProp2").style.display = 'none';
document.getElementById("realProp3").style.display = 'none';
};
function Additem() {
document.getElementById("realProp1").style.display = "";
};
</script>
How can I make one div tag visible at each button click.
You can use :eq() to compare which div to show and save some variable for holding the last count value or you can just use $("div[id^=realProp]").filter(":hidden").first().show() for filtering the hidden divs and showing first div always.
Demo Code :
$('div[id^=realProp]').hide();
var count = 0;
$('.show_div').on('click', function() {
$('div[id^=realProp]:eq(' + count + ')').show(); //show div
count++; //for next div to show
//or without count ..use below
//show first div..by filtering hidden divs
//$("div[id^=realProp]").filter(":hidden").first().show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" class="btn btn-primary show_div">Add Item</button>
Without jquery :
var length = document.querySelectorAll("div[id^='realProp']").length;
var count = 1; //for holding last visible div count
function AddItem() {
if (count <= length) {
document.getElementById("realProp" + count).style.display = "block"; //show..
count++;
} else {
console.log("No more divs")
}
};
div[id^='realProp'] {
display: none
}
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>
let count = 1;
window.onload = function() {
document.getElementById("realProp1").style.display = 'none';
document.getElementById("realProp2").style.display = 'none';
document.getElementById("realProp3").style.display = 'none';
};
function AddItem() {
for (let i = 1; i < 4; i++) {
document.getElementById("realProp" + i).style.display = "none";
}
document.getElementById("realProp" + count).style.display = "";
if (count <3 ){
count++;
} else {
count = 1;
}
};
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>

buttons are not show assigning to vaules to graphing calculator

I not sure if this supper basic or not but I am trying to add number values to some buttons through onclick functions. All done in html and javascript.
It can display the numbers fine but doesn't seem to make the numbers have any values to them if that makes sense. I just keep getting null values. Is it because of all the onclick events?
Below is the html.
var getvaule7.value = document.getElementsByClassName("7");
getvaule7.value = 7;
var getvaule8 = document.getElementsByClassName("8");
getvaule8.value = 8;
var getvaule9 = document.getElementsByClassName("9");
getvaule9.value = 9;
var getvaule4 = document.getElementsByClassName("4");
getvaule4.value = 4;
var getvaule5 = document.getElementsByClassName("5");
getvaule5.value = 5;
var getvaule6 = document.getElementsByClassName("6");
getvaule6.value = 6;
var getvaule1 = document.getElementsByClassName("1");
getvaule1.value = 1;
var getvaule2 = document.getElementsByClassName("2");
getvaule2.value = 2;
var getvaule3 = document.getElementsByClassName("3");
getvaule3.value = 3;
var getvaule0 = document.getElementsByClassName("0");
getvaule0.value = 0;
function number7() {
document.getElementById("show").value = getvaule7.value;
}
console.log(number7());
function number8() {
document.getElementById("show").value = getvaule8.value;
}
function number9() {
document.getElementById("show").value = getvaule9.value;
}
function number4() {
document.getElementById("show").value = getvaule4.value;
}
function number5() {
document.getElementById("show").value = getvaule5.value;
}
function number6() {
document.getElementById("show").value = getvaule6.value;
}
function number1() {
document.getElementById("show").value = getvaule1.value;
}
function number2() {
document.getElementById("show").value = getvaule2.value;
}
function number3() {
document.getElementById("show").value = getvaule3.value;
}
function number0() {
document.getElementById("show").value = getvaule0.value;
}
<body>
<h1 style="text-align: center;">
Graphing Calculator from Scratch
</h1>
<div id="Text box" style="text-align: center;">
<input type="text" name="" id="show">
</div>
<br></br>
<div style="text-align:center" id="click-row">
<div id="row one" ><button type="button" class="7" onclick="number7()" value=7> 7</button>
<button type="button" class="8" onclick="number8()" >8</button>
<button type="button" class="9" onclick="number9()">9</button>
</div>
<div id="row two"><button type="button" class="4" onclick="number4()">4</button>
<button type="button" class="5" onclick="number5()">5</button>
<button type="button" class="6" onclick="number6()">6</button>
</div>
<div id="row three"><button type="button" class="1" onclick="number1()">1</button>
<button type="button" class="2" onclick="number2()">2</button>
<button type="button" class="3" onclick="number3()">3</button>
</div>
<button type="button" class="0" onclick="number0()">0</button>
<button type="button" class=".">.</button>
<button type="button" class="𝝅">𝝅</button>
<div id="row 5">
<div id="row 5"><button type="button" class="+/-">+/-</button>
<div id="row 5"><button type="button" class="+">+</button>
<div id="row 5"><button type="button" class="-">-</button>
<button type="button" onclick="enter()" >=</button>
</div>
<br>
<button onclick="document.getElementById('show').value = ''" style="text-align:center;">Clear input field</button>
</div>
</div>
</div>
</div>
</body>
</html>
First, the way you are going about it is not the best way to do it but since you are just getting started I will not confuse you and just correct your code instead.
There are a couple of errors in your code
button does not have value it has innerText property. value property
is for input tags only.
use += when you are trying to set value to
show input since = will erase what was in it before hands.
you have not defined enter() function that was it gives you that error you
have to create enter function first
another thing is document.getElementsByClassName("7") does not retun one element like getElementById but it returns an array that is why if you are using gelementsByClassName you have to also write [number] where number is the index of your element in the returned array. in your case number is 0 which means the first element in the array.
another one is you dont need to use getValue7.value = document.get... since you are using it just for storing the element you can just use getValue = document.getlE.....
and you html tag nesting was incorrect please nest them correctly.
To help you understand the correct solution. I wrote minimum code for you project down below. please compare it with your code to see what is wrong,
var getvaule7 =document.getElementsByClassName("7")[0];
var getvaule8 =document.getElementsByClassName("8")[0];
var getvaule9 =document.getElementsByClassName("9")[0];
var getPlus = document.getElementsByClassName("plus")[0];
function number7(){
document.getElementById("show").value += getvaule7.innerText;
}
function number8(){
document.getElementById("show").value += getvaule7.innerText;
}
function number9(){
document.getElementById("show").value += getvaule7.innerText;
}
function plus(){
document.getElementById("show").value += getPlus.innerText;
}
function enter(){
document.getElementById("show").value = eval(document.getElementById("show").value);
}
<h1 style="text-align: center;">
Graphing Calculator from Scratch
</h1>
<div id="Text box" style="text-align: center;">
<input type="text" name="" id="show">
</div>
<br></br>
<div style="text-align:center" id="click-row">
<div id="row one" >
<button type="button" class="7" onclick="number7()" value=7>7</button>
<button type="button" class="8" onclick="number8()" >8</button>
<button type="button" class="9" onclick="number9()">9</button>
</div>
<div id="row 5">
<button type="button" onclick="plus()" class="plus">+</button>
<button type="button" onclick="enter()" >=</button>
</div>
<br>
<button onclick="document.getElementById('show').value = ''" style="text-align:center;">Clear input field</button>
function load() {
let num7=document.getElementById("7").addEventListener('click',()=>{
document.querySelector(".show").value+=7;
})
let num8=document.getElementById("8").addEventListener('click',()=>{
document.querySelector(".show").value+=8;
})
var userEnter1= parseInt(document.querySelector(".show").value);
var userEnter2=parseInt(document.querySelector(".show").value);
[0]
// HOW TO MAKE SURE THAT A USER CAN INPUT ANOTHER DATA AFTER PRESSING THE +
let add=document.getElementById("add").addEventListener('click',()=>{
document.querySelector(".show").value+="+";
userEnter1+userEnter2;
})
const equals=document.getElementById("equals").addEventListener('click',()=>{
console.log( userEnter1+userEnter2);
});
}
window.onload = load;
}
window.onload = load;
<body>
<h1 style="text-align: center;">
Graphing Calculator from Scrach
</h1>
<div id="Text box" style="text-align: center;">
<input type="text" class="show" id="clear">
</div>
<br></br>
<div style="text-align:center" id="click-row">
<div id="activate" >
<div id="row one">
<input type="Button" id="7" class="num7" value="7" > </input>
<input type="Button" id="8" value="8" > </input>
</div>
<div id="row 2">
<input type="Button" id="add" value="+" onclick="" > </input>
<input type="Button" id="equals" value="=" > </input>
</div>
</div>
<br>
<button onclick="document.getElementById('clear').value = ''" style="text-align:center;">Clear input field</button>
</div>
</div>
</div>
</div>
</body>
</html>

What will be the Javascript code for this for changing the ID of each tag while making a clone every time?

I want to clone the template and show it to the <div id= "wrapper"> with different ID every time I make a clone. When I press the add-new-project button a new template is shown with different "ID" every time.
Javascript code:
$("document").ready(function () {
var cloneCntr = 1;
var i = 0;
$("#projectData").on('click', function () {
$('template').children().each(function () {
this.id = this.id+ this.i;
});
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
i++;
$('#wrapper').append(clon);
});
});
Html code:
<form id="projectForm">
<div class="container">
////// ---------------------code-------//// <br>
<br>
<h4>Project Experience</h4>
<hr>
<template id="template">
<br>
<br>
<div class="form-row">
---------Template Code-------
</div>
</div>
<hr>
</template>
</div>
<div id="wrapper" class="container">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div class="container">
<button type="button" id="projectData" class="btn btn-primary">Add New Project</button>
</div>
</body>
</html>
I want to replace every tag "id" in the template, every time when I make a clone of this.
Here's an example of how this could work for you.
See a demo here: https://jsfiddle.net/o76pqxyw/
Here's a screenshare, showing how the IDs change: https://www.loom.com/share/4a1556c4bb5c4422ad1d4b20a12a638a
HTML
<div id="template-form">
<p><label>First Name</label> <input type="text" id="first-name" /></p>
<p><label>Last Name</label> <input type="text" id="last-name" /></p>
</div>
<button id="btn">Add New User</button>
<div id="container"></div>
Javascript
const button = $('#btn');
const target = $('#container');
let counter = 0;
$(button).on('click', () => {
const template = $('#template-form');
const copy = $(template).clone();
counter++;
const elements = $(copy).find('input');
$(elements).each(function(index) {
const currentId = $(this).attr('id');
const newId = currentId + '-' + counter;
$(this).attr('id', newId);
});
$(target).append(copy);
})

Trying to add a submit button using jQuery But only on the last page

I am trying for the submit button to show up on the last page, each page has one set of question and to move forward or backward there's the Next and Back buttons. On the last page is where I want my submit button to be placed and when clicked I want some output revealing the submit button was clicked.
Here is my code ....
if (i.Question_Type == "DROPDOWN")
{
<div class="container text-center">
<div class="row idrow" data-questions="#counter">
#{counter++;
}
<div id="question1" class="form-group">
<label class="lab text-center" for="form-group-select">
#i.Question_Order #Html.Raw(#i.Question)
</label>
<select class="form-control" id="form-group-select">
#for (int x = 1; x <= Convert.ToInt32(i.Question_SubType); x++)
{
var t = x - 1;
if (i.qOps != null)
{
<option> #i.qOps.options[t]</option>
}
else
{
<option> #x</option>
}
}
</select>
</div>
</div>
</div>
}
if (i.Question_Type == "RADIO")
{
<div class="container">
<div class="row idrow" data-questions="#counter">
#{counter++;
}
<div class="form-group">
<label class="lab" for="questions">
#i.Question_Order #i.Question
</label>
<div class="row">
<div class="col-xs-12">
<div id="question1" class="radio-inline">
#for (int x = 1; x <= Convert.ToInt32(i.Question_SubType); x++)
{
var t = x - 1;
if (i.qOps != null)
{
<label class="radio-inline"><input type="radio" name="question"> #i.qOps.options[t]</label>
}
else
{
<label class="radio-inline"><input type="radio" min="0" max="#x" name="question"></label>
}
}
</div>
</div>
</div>
</div>
</div>
</div>
}
if (i.Question_Type == "CHECKBOX")
{
for (int y = 1; y <= Convert.ToInt32(i.Question_SubType); y++)
{
#*<div class="container">
<div class="row">
<label>#y</label> <input type="checkbox" name="question">
</div>
</div>*#
}
}
}
<div class="azibsButtons">
<button type="button" id="previous" class="btn btn-primary pull-left">Prev</button>
<button type="button" id="next" class="btn btn-primary pull-right">Next</button>
<button type="button" id="submit" class= // what to put here??
</div>
<script>
$(document).ready(function () {
ShowTheelement(0);
$("#previous").addClass('hidden');
var dataVal = 0;
$("#next").click(function () {
dataVal++;
$("#previous").removeClass('hidden');
dataVal == $(".idrow[data-questions]").length-1 ? $(this).addClass('hidden') : $(this).removeClass('hidden');
ShowTheelement(dataVal);
});
$("#previous").click(function () {
dataVal--;
$("#next").removeClass('hidden');
dataVal == 0 ? $(this).addClass('hidden') : $(this).removeClass('hidden');
ShowTheelement(dataVal);
});
});
function ShowTheelement(dataVal) {
$(".idrow").addClass('hidden');
$(".idrow[data-questions='" + dataVal + "']").removeClass('hidden');
}
</script>
When I understood you correctly, you could just use a similar approach as for your other buttons.
basic button setup
<div class="azibsButtons">
<button type="button" id="previous" class="btn btn-primary pull-left">Prev</button>
<button type="button" id="next" class="btn btn-primary pull-right">Next</button>
<button type="button" id="submit" class="hidden btn btn-primary pull-right">Submit</button>
</div>
in your document ready function
$("#next").click(function () {
dataVal++;
$("#previous").removeClass('hidden');
dataVal == $(".idrow[data-questions]").length-1 ? $(this).addClass('hidden') : $(this).removeClass('hidden');
ShowTheelement(dataVal);
if (dataVal == $(".idrow[data-questions]").length-1) {
$("#submit").removeClass('hidden');
}
});
$("#previous").click(function () {
dataVal--;
$("#next").removeClass('hidden');
dataVal == 0 ? $(this).addClass('hidden') : $(this).removeClass('hidden');
ShowTheelement(dataVal);
if (dataVal == $(".idrow[data-questions]").length-2) {
$("#submit").addClass('hidden');
}
});
This is not a very nice code but should help you with your problem.
good luck
Awesome work dude, but i guess we were just missing one last thing which kept showing the submit button on every page but now its not because of this piece of code ....
<script>
$(document).ready(function () {
ShowTheelement(0);
$("#previous").addClass('hidden');
$("#submit").addClass('hidden');
var dataVal = 0;
....

create textboxes and Insert data at page loading

I would like to know how can I create textboxes and insert data at page load.
What I'm trying to do is open an array string from a database, create the textboxes and populate the textboxes at page load.
I have an array string from an ms sql database that looks something like this
test,test;bla;bla2;test44;test55;test66
I separated each individual array with ; and I would like to create textboxes and insert the values into a textbox, one-by-one, so the end result would look like this:
I don't know how to do it using the code below.
Whatever I try I mess up the add/remove functions or I end up cloning all textboxes when the plus button is clicked.
THANKS
SEE CODE BELOW OR GO TO https://jsfiddle.net/kj3cwww0
<script type='text/javascript'>//<![CDATA[
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('#template_add_form'),
formArray = [ clone($template) ], // init array with first row
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
updateForm(); // first init. of form
});
//]]>
</script>
<script id="template_add_form" type="text/template">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</script>
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
FORM SUBMIT CODE:
<body>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
......the rest of the existing code goes here...
</div>
</form>
</body>
CALLING IT VIA CLASSIC ASP:
if strComp(Request.Form("action"), "submit")= 0 then
Response.write("IT WORKS")
end if
Here is a solution that works :
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),
formArray = [ ], // init array enpty
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
$('#template_add_form').remove();
});
.entry:not(:first-of-type)
{
margin-top: 10px;
}
.glyphicon
{
font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
<div id="template_add_form" type="text/template" style="display: none;">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</div>
</form>
</body>
Here's what I changed to your code :
Changed the template which was a <script> to a <div>, and hid it by default using style="display: none;" :
<div id="template_add_form" type="text/template" style="display: none;">
Initialized array empty, so that we can put our own first line : formArray = [ ],
Created a function to add a string in the form :
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
At the end, I added some example data, then pushed an empty line and updated the form :
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
EDIT : I also deleted the template div at the end so that it isn't taken into the form when you submit :
$('#template_add_form').remove();
To be able to do that, I cloned it entirely at start :
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),

Categories