I am rendering out different dates I have not reported a time for.
If the time spans over more than 1 month it will render out each month and the dates under the right tab. And if the dates only is within 1 month it will only render out the dates.
But my issue is when the dates are not under a tab my "Select" all checkbox doesn't work.
This is my script:
$(function () {
$(".selectAll").on("click", function () {
if ($(this).is(':checked')) {
$(this).closest('.panel-default').find("input[name='isoDate']").prop('checked', this.checked);
$('input[name="isoDate"]').trigger('change');
} else {
$(this).closest('.panel-default').find("input[name='isoDate']").prop('checked', false);
$('input[name="isoDate"]').trigger('change');
}
});
});
And this is the view:
#if (ViewBag.MissingDays != null)
{
int i = 0;
var months = ((List<DateTime>)ViewBag.MissingDays).GroupBy(x => x.Month);
IEnumerable<IGrouping<int, DateTime>> groups = months as IList<IGrouping<int, DateTime>> ?? months.ToList();
foreach (var group in groups)
{
i++;
var month = CultureInfo.CreateSpecificCulture("sv-SE").DateTimeFormat.GetMonthName(group.Key);
if (groups.Count() > 1)
{
<div class="panel-group accordion" id="accordion1">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion1" href="#collapse_#i">
#month
</a>
</h4>
</div>
<div id="collapse_#i" class="panel-collapse collapse">
<div class="panel-body">
<div class="col-md-12">
<label>
<input type="checkbox" class="selectAll" name="all"/>
Välj alla.
</label>
<br/>
#foreach (var date in group)
{
var isoDate = date.ToString("yyMMdd");
var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
<label style="padding-left: 10px">
<input type="checkbox" class="selectedId" name="isoDate" value="#isoDate"/>#day-#isoDate
</label>
}
</div>
</div>
</div>
</div>
</div>
}
else
{
<div class="col-md-12">
<label>
<input type="checkbox" class="selectAll" name="all" />
Välj alla.
</label>
#foreach (var date in group)
{
var isoDate = date.ToString("yyMMdd");
var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
<label style="padding-left: 10px">
<input type="checkbox" class="selectedId" name="isoDate" value="#isoDate" />#day-#isoDate
</label>
}
</div>
}
}
}
Assuming that you are facing issue only in case when dates are within 1 month so there will not be any tab. Simply dates will be rendered.
Please try with following modified script:
$(function () {
$(".selectAll").on("click", function () {
if ($(this).is(':checked')) {
if($(this).closest('.panel-default').length > 0)
$(this).closest('.panel-default').find("input[name='isoDate']").prop('checked', this.checked);
else
$("input[name='isoDate']").prop('checked', this.checked);
$('input[name="isoDate"]').trigger('change');
} else {
if($(this).closest('.panel-default').length > 0)
$(this).closest('.panel-default').find("input[name='isoDate']").prop('checked', false);
else
$("input[name='isoDate']").prop('checked', false);
$('input[name="isoDate"]').trigger('change');
}
});
});
Related
If searched keyword matches I am able to show the matched input text and its related div with category name. Now what I am trying is to search over category names as well.
If searched keyword matches with the category name this div should visible. also if searched keyword matches with the input names this is also visible with its category name.
$('.bar-input').on('keyup', function() {
var search_input = $(this).val().toLowerCase();
var tags = $('.wrap label');
var count = tags.length;
var text_input = $(this).val().length;
var category = $('.category-type');
// // searching for tags
for (i = 0; i < count; i++) {
if (!search_input || tags[i].textContent.toLowerCase().indexOf(search_input) > -1) {
tags[i].parentNode.style['display'] = 'block';
} else {
tags[i].parentNode.style['display'] = 'none';
}
}
// If no tags found category will be hidden
$(".category").not(".stcw-screen").map(function() {
let flag = true;
$(this).find('.wrap').map(function() {
if ($(this).css("display") != "none") {
flag = false;
}
});
if (flag) {
$(this).css("display", "none");
} else {
$(this).css("display", "block");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="bar-input" type="text" placeholder="search">
<div class="category">
<div class="category-name">
<h5>Country</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">America</label>
</div><div class="wrap">
<label><input type="checkbox">France</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Sports</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">Football</label>
</div><div class="wrap">
<label><input type="checkbox">Cricket</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Operating system </h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">linux</label>
</div><div class="wrap">
<label><input type="checkbox">windows</label>
</div>
</div>
</div>
To do what you require you can loop through each category and first determine if the .category-type matches the search term using a case-insensitive implementation of :contains and then display that section with all options visible, or if not you can look at each option in turn using the same :icontains() selector and show them individually.
The logic would look something like this:
// case-insensitive :contains implementation (credit: https://stackoverflow.com/a/8747204/519413)
jQuery.expr[':'].icontains = (a, i, m) => $(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
var $categories = $('.category');
var $types = $('.category-type');
$('.bar-input').on('input', function() {
var search_input = $(this).val().toLowerCase().trim();
if (search_input.length == 0) {
// no search term entered, reset state to show all items
$('.wrap label').add($types).show()
return;
}
$categories.each((i, category) => {
let $cat = $(category);
let $type = $cat.find('.category-type').hide();
let $labels = $cat.find('.wrap label').hide();
if ($type.is(`:icontains("${search_input}")`)) {
// match on category type, show category-type and all child options
$type.add($labels).show();
} else {
// no match on category, show only if match on child option
let $matches = $labels.filter(`:icontains("${search_input}")`).show();
$type.toggle($matches.length > 0);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="bar-input" type="text" placeholder="search">
<div class="category">
<div class="category-type">
<h5>Country</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">America</label>
</div>
<div class="wrap">
<label><input type="checkbox">France</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Sports</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">Football</label>
</div>
<div class="wrap">
<label><input type="checkbox">Cricket</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Operating system </h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">linux</label>
</div>
<div class="wrap">
<label><input type="checkbox">windows</label>
</div>
</div>
</div>
how can I add the class "disabled" to the second checkbox if the first one is selected and vice versa.
I don't know where I'm wrong, this is my code, in which I imagined two functions to include where I will turn off the secondary checkbox in each. (maybe it can in one function for sure, but I don't know), this is my example, if someone can correct me where I went wrong, thank you.
function disableNewmobileOption(ev) {
ev.preventDefault();
var inputElementLabel = $(ev.currentTarget);
var inputElement = inputElementLabel.siblings("input");
if (inputElement.is(':checked')) {
if (inputElement.attr("id") === "b_mobnr") {
$(".newmobile .circle-buttons").addClass("disabled");
} else {
$(".b_mobnr .circle-buttons").removeClass("disabled");
}
}
}
function disableBMobOption(ev) {
ev.preventDefault();
var inputElementLabel = $(ev.currentTarget);
var inputElement = inputElementLabel.siblings("input");
if (inputElement.attr("id") === "newmobile") {
$(".b_mobnr .circle-buttons").addClass("disabled");
} else {
$(".newmobile .circle-buttons").removeClass("disabled");
}
}
<div class="row">
<div class="col-sm-4 newmobile">
<h4>Optionen</h4>
<span class="circle-buttons">
<input type="checkbox" name="b_mobnr" id="b_mobnr" value="0">
<label for="b_mobnr" onclick="disableNewmobileOption(event)">Mobile Option</label>
<div class="check square-check"></div>
</span>
</div>
<div class="col-sm-12 b_mobnr">
<span class="circle-buttons">
<input type="checkbox" name="newmobile" id="newmobile" value="0">
<label for="newmobile" onclick="disableBMobOption(event)">Newmobile Option </label>
<div class="check square-check"></div>
</span>
</div>
</div>
You can use .not() to add disabled class to other span tag when your checkbox is checked.Other way would be passing this inside your function call then depending on if the checkbox is checked add class to other span.
Demo Code :
/*$(".circle-buttons input[type=checkbox]").on("change", function() {
$(".circle-buttons").removeClass("disabled") //remove from all
if ($(this).is(":checked")) {
$(".circle-buttons").not($(this).closest(".circle-buttons")).addClass("disabled") //other span tag
}
})*/
function disableNewmobileOption(el) {
var inputElement = $(el);
//remove class from all
$(".circle-buttons").removeClass("disabled");
//check if checkbox is checked
if (inputElement.is(':checked')) {
//add class to other
$(".b_mobnr .circle-buttons").addClass("disabled");
}
}
function disableBMobOption(el) {
var inputElement = $(el);
$(".circle-buttons").removeClass("disabled");
if (inputElement.is(':checked')) {
$(".newmobile .circle-buttons").addClass("disabled");
}
}
.disabled {
color: grey;
pointer-events: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-sm-4 newmobile">
<h4>Optionen</h4>
<span class="circle-buttons">
<!--aded click event on checkbox-->
<input type="checkbox" name="b_mobnr" id="b_mobnr" onclick="disableNewmobileOption(this)" value="0">
<label for="b_mobnr" >Mobile Option</label>
<div class="check square-check"></div>
</span>
</div>
<div class="col-sm-12 b_mobnr">
<span class="circle-buttons">
<input type="checkbox" name="newmobile" id="newmobile" onclick="disableBMobOption(this)" value="0">
<label for="newmobile">Newmobile Option </label>
<div class="check square-check"></div>
</span>
</div>
</div>
I want to create a page where I can filter products with checkboxes but also to keep the filter choices on page reload.
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="1" value="option1" >
<label for="1">Adidas</label>
</div>
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="2" value="option2" >
<label for="1">Nike</label>
</div>
<script>
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
$checkboxes = $("#checkbox-container :checkbox");
$checkboxes.on("change", function(){
$checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
// On page load
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
});
$('input[type="checkbox"]').change(function() {
if ($('input[type="checkbox"]:checked').length > 0) {
$('.products >div').hide();
$('input[type="checkbox"]:checked').each(function() {
$('.products >div[data-category=' + this.id + ']').show();
});
} else {
$('.products >div').show();
}
});
</script>
I have found both jquery scripts and they both work fine by themselves. By this I mean that I can get to filter the products when checking/unchecking the checkboxes. When checking a checkbox and reloading the page, the checkbox is correctly checked but products has not been filtered. So I need to merge the 2 scripts so that products also will be filtered when reloading the page with a checked checkbox.
Hope someone can guide me a bit here.
--- UPDATE ---
I have created an example here: maxie.dk/filter.php
1) Tick a checkbox
2) Product filter is activated and only products with matching value is displayed
3) Refresh page
4) Checkbox checked is kept as it should but all products are now again visible. Only matching products to the ticked checkbox should be visible.
Thanks
If I get your issue right - you want to move your "business logic" that happens on each input change to a separate function so that it can be executed also upon page reload.
...
// On page load
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
});
// your business logic
function updateProducts() {
if ($('input[type="checkbox"]:checked').length > 0) {
$('.products >div').hide();
$('input[type="checkbox"]:checked').each(function() {
$('.products >div[data-category=' + this.id + ']').show();
});
} else {
$('.products >div').show();
}
}
$('input[type="checkbox"]').change(function() {
// execute for each change
updateProducts();
});
// execute on page load
updateProducts()
I have re-write this such that it will update the localstorage and also check and show product that is save in localstorage. It will also remove or show product on checked. Check it out.
<div class="col-xs-12 col-sm-12">
<div class="breadcrumb" id="checkbox-container">
<h4 class="visible-xs"></h4>
<span class="hidden-xs"></span>
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="1" value="1" />
<label for="1">Adidas</label>
</div>
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="2" value="2" />
<label for="2">Reebok</label>
</div>
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="3" value="3" /> <label for="3">Nike</label>
</div>
´
</div>
</div>
<div class="products">
<div
class="col-xs-6 col-ms-4 col-sm-4 col-md-4 col-lg-3 padding-btm "
data-category="1" >
PRODUCT 1
</div>
</div>
<div class="products">
<div
class="col-xs-6 col-ms-4 col-sm-4 col-md-4 col-lg-3 padding-btm "
data-category="1">
PRODUCT 2
</div>
</div>
<div class="products">
<div
class="col-xs-6 col-ms-4 col-sm-4 col-md-4 col-lg-3 padding-btm "
data-category="2"
>
PRODUCT 3
</div>
</div>
<div class="products">
<div
class="col-xs-6 col-ms-4 col-sm-4 col-md-4 col-lg-3 padding-btm "
data-category="3"
>
PRODUCT 4
</div>
</div>
var checkedValues =JSON.parse(localStorage.getItem('checkboxValues')) || [],
$checkboxes = $("#checkbox-container input[type=checkbox]");
function loadPrevious(){
if(checkedValues.length>0){
$("div.products > div").hide();
$.each(checkedValues,function(i,v){
$("#checkbox-container input[type=checkbox]#" + v ).prop('checked',true);
$('.products >div[data-category=' + v + ']').show();
})
}
}
loadPrevious();
$checkboxes.change(function(e) {
e.preventDefault();
if($(this).prop("checked") == true){
checkedValues.push($(this).attr("id"));
loadPrevious();
localStorage.setItem("checkboxValues", JSON.stringify(checkedValues));
}else{
var checkId = $(this).attr("id"),
arr = JSON.parse(localStorage.getItem('checkboxValues'));
$('.products >div[data-category=' + checkId + ']').hide();
var newArr = $(arr).not([checkId]).get();
localStorage.setItem("checkboxValues", JSON.stringify(newArr));
}
});
See the demo here
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;
....
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'))),