Repopulate form input after delete another field - javascript

Good day, i have this section of javascript that's causing me trouble
https://jsfiddle.net/o5x8qgvt/2/
When i add a new field the position gets incremented when i delete a field the position is repopulated but on product name it doesn't repopulate the fields it gives me blank even if i added data in each of them. Can you please help me out?
Javascript:
// setup an "add a tag" link
var $addTagLink = $('<button href="#" class="btn btn-info add_tag_link">Adauga Produs</button>');
$('.form-buttons > .btn-group').prepend($addTagLink);
var $newLinkLi = $('.append-me');
jQuery(document).ready(function() {
// Get the ul that holds the collection of product-group
var $collectionHolder = $('#products-group');
// add the "add a tag" anchor and li to the product-group ul
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addTagLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a new tag form (see code block below)
addTagForm($collectionHolder, $newLinkLi);
typeInitialize();
});
});
function regenerateTagList() {
var vals = $('.product-group > .product-counter > input').toArray().map(function(v, i) {return v.value;});
var products = $('.product-group > .product-name > span > input:last').toArray().map(function(v, i) {return v.value;});
console.log(products);
$('.product-group').remove();
$('#products-group').data('index', 1);
for (var i = 0; i < vals.length; i++) {
if (vals[i] !== i + 1) {
vals[i] = i + 1;
}
addTagForm($('#products-group'), $newLinkLi);
typeInitialize();
$('.product-group > .product-counter > input:last').val(vals[i]);
$('.product-group > .product-name > span > input:last').val(products[i]);
}
}
function addTagForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
if (index === 0) {
index = 1;
}
// Replace '$$name$$' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<tr class="product-group"></tr>').append(newForm);
// also add a remove button, just for this example
//$('<button type="button" class="product-highlight btn btn-primary">Highlight</button>
// <button type="button" class="remove-tag btn btn-primary">Sterge</button>').appendTo($newFormLi);
$newLinkLi.append($newFormLi);
// handle the removal, just for this example
$('.remove-tag').click(function(e) {
e.preventDefault();
$(this).closest('tr').remove();
regenerateTagList();
return false;
});
$('.product-highlight').on('click', function(e) {
e.preventDefault();
$(this).closest('tr').toggleClass('toggle-highlight');;
});
}
// Initialize Typeahead
function typeInitialize() {
// Create typeahead instance
var url = Routing.generate('offer_ajax_search', {
name: 'WILDCARD'
});
// Trigger typeahead + bloodhound
var products = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) {
console.log('fired');
return obj.u_name;
},
prefetch: '/export/json/products.json',
remote: {
url: url,
wildcard: 'WILDCARD',
}
});
products.initialize();
$('.product-group').find('.typeahead:last').typeahead({
minLength: 3,
highlight: true,
limit: 10,
}, {
name: 'product',
display: 'u_name',
source: products.ttAdapter()
}).on('typeahead:select', function(e, datum) {
e.preventDefault();
/* Act on the event */
var information = '<div class="col-md-2"><label for="boxCode" class="label-control">BEX Code</label><input class="form-control" type="text" disabled="true" value="' + datum.u_bexCode + '"/></div>';
information += '<div class="col-md-2"><label for="base-price">Pret de baza</label><input class="form-control " type="text" disabled="true" value="' + datum.u_image + '"/></div>';
var div = $(this).parent().closest('.form-group').find('.product-information');
$(div).empty().append(information);
}).on('typeahead:autocomplete', function(e, datum) {
e.preventDefault();
/* Act on the event */
var information = '<div class="col-md-2"><label for="boxCode" class="label-control">BEX Code</label><input class="form-control" type="text" disabled="true" value="' + datum.u_bexCode + '"/></div>';
information += '<div class="col-md-2"><label for="base-price">Pret de baza</label><input class="form-control " type="text" disabled="true" value="' + datum.u_image + '"/></div>';
var div = $(this).parent().closest('.form-group').find('.product-information');
$(div).empty().append(information);
});
$("input[type='text']").on("click", function() {
$(this).select();
});
}
HTML:
<div class="row">
<div class="col-md-12">
<form name="offer" method="post" action="/app_dev.php/offer-generator/new/submited" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label required" for="offer_name">Name</label><div class="col-sm-10"><input type="text" id="offer_name" name="offer[name]" required="required" maxlength="255" class="form-control"></div>
</div>
<div id="products-group" data-prototype="<td class="product-counter col-md-1"><input type="text" id="offer_products___name___position" name="offer[products][__name__][position]" disabled="disabled" required="required" class="counter form-control" value="__name__" /></td>
<td class="product-name"><input type="text" id="offer_products___name___name" name="offer[products][__name__][name]" required="required" class="typeahead product form-control" name="product" id="products" data-provider="product" placeholder="Nume Produs" autocomplete="false" /></td>
<td class="col-md-1"><input type="text" id="offer_products___name___price" name="offer[products][__name__][price]" required="required" class="form-control" /></td>
<td class="col-md-1"><input type="text" id="offer_products___name___quantity" name="offer[products][__name__][quantity]" required="required" class="form-control" /></td>
<td class="product-action">
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="product-highlight btn btn-warning">Highlight</button>
<button type="button" class="remove-tag btn btn-danger">delete</button>
</div>
</td>
"><table class="table table-striped table-hover table-bordered append-me">
<thead>
<tr>
<th class="col-md-1">Position</th>
<th>Product</th>
<th class="col-md-1">Price</th>
<th class="col-md-1">Quantity</th>
<th class="col-md-2">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table></div>
</form></div>
<div class="form-buttons">
<div class="btn-group" role="group" aria-label="..."><button href="#" class="btn btn-info add_tag_link">Add Product</button>
<button type="submit" id="offer_save" name="offer[save]" class="btn-default btn">Create Offer</button>
<button type="submit" id="offer_send_email" name="offer[send_email]" class="btn-default btn">Send Email</button>
<button type="submit" id="offer_export_excel" name="offer[export_excel]" class="btn-default btn">Export Excel</button>
<button type="submit" id="offer_export_pdf" name="offer[export_pdf]" class="btn-default btn">Export PDF</button>
</div>
</div>
<div class="form-group"><div class="col-sm-2"></div><div class="col-sm-10"><div id="offer_products" data-prototype="<div class="form-group"><label class="col-sm-2 control-label required">__name__label__</label><div class="col-sm-10"><div id="offer_products___name__"><div class="form-group"><label class="col-sm-2 control-label required" for="offer_products___name___pricePerLine">Line Total</label><div class="col-sm-10"><input type="text" id="offer_products___name___pricePerLine" name="offer[products][__name__][pricePerLine]" required="required" class="form-control" /></div>
</div></div></div>
</div>"></div></div>
</div><input type="hidden" id="offer__token" name="offer[_token]" class="form-control" value="cSVdt50kupA_BwFeY4T43PslnfjiA-UgjT4EA_HBdqs">
</div>

Related

How can I add an incrementing id="" attribute to the following JavaScript generated HTML form?

I have managed to come up with the following JavaScript and HTML but now I am stuck. I want to be able to add an id="" attribute to the fields and have them numbered as I add more fields with the '+ Add' button.
I've been playing around with this but have not had any success yet. Could someone give me some suggestions or offer some solutions to this issue?
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><table width="100%"><tr><td><input type="text"
name="field_name[]" value="" class="form-control" style="width:98%;"
placeholder="Role"/></td><td><input type="text" name="field_name[]" value=""
class="form-control" style="width:100%;" placeholder="Name"/></td></tr></table>
<a href="javascript:void(0);" class="remove_button"><button type="button"
class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> -
Remove </button></a></div>';
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%"/>
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%"/>
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field">
<button style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role </button>
</a>
</div>
</div>
You can try this snippet:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
$(document).ready(function () {
var x = 1; //Initial field counter is 1
var idCounter = 0;
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
function fieldHTML(id) {
return '<div><table width="100%"><tr><td>id:' + id + '<input type="text"' +
'id="role-' + id + '" name = "field_name[]" value = "" class="form-control" style = "width:98%;"' +
'placeholder = "Role" /></td > <td><input type="text" id="name-' + id + '" name="field_name[]" value=""' +
'class="form-control" style="width:100%;" placeholder="Name" /></td></tr ></table >' +
'<a href="javascript:void(0);" class="remove_button"><button type="button"' +
'class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> - Remove </button></a></div >';
}
//Once add button is clicked
$(addButton).click(function () {
//Check maximum number of input fields
if (x < maxField) {
$(wrapper).append(fieldHTML(idCounter++)); //Add field html
x++; //Increment field counter
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%" />
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%" />
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field"><button
style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role
</button></a>
</div>
</div>
Note, I have created a new variable idCounter to keep the id unique even when you remove a row. Otherwise, it might create elements with duplicate ids.
This is just one quick way, but there are many other ways this can be achieved. The code can be made mode tidy and readable.

Prevent form submission by checking every dynamically created text boxes are empty

Here I am trying to check each and every dynamically created textboxes whether it is empty or not before the form submission.
Here is the HTML code,
<form>
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control test_id" type="text" style="width:200px" id="test_id" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);"> </td>
<td> <input type="text" style="width:300px" class="form-control test_name" readonly="" id="test_name" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"></td>
<td> <input type="text" style="min-width:100px" class="form-control amount" name="amount" readonly=""> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
<span id="test_id_info" class="info text-danger"></span>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Other Information</label>
<textarea class="form-control" id="description"></textarea>
</div>
</div>
</div>
<div class="text-center m-t-20">
<input type="button" class="btn btn-primary submit-btn" name="pay"value="Generate Invoice" id="pay">
</div>
</form>
Here is the Ajax code
$(document).ready(function(){
var count=0;
$(document).on('click','#add',function() {
count++;
var html= '';
html += '<tr id="trrows">';
html += '<td id="testid"> <input id="test_id" class="form-control test_id" type="text" style="width:200px" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);" onblur="sum(this);" onkeyup="sum(this);" onchange="sum(this);"> </td>';
html += '<td id="testname"> <input id="test_name" type="text" style="width:300px" class="form-control test_name" readonly="" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>';
html += '<td id="amounts"> <input id="amount" name="amount" type="text" style="min-width:150px" class="form-control amount" readonly="" > </td>';
html += '<td><center> <i class="fa fa-trash-o"></i></center> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click','.remove',function() {
$(this).closest("#trrows").remove();
});
});
// generate bill
$(document).on('click', '#pay', function () {
var test_id = new Array();
$('input[id="test_id"]').each(function() {
test_id.push(this.value);
});
var amount = new Array();
$('input[name="amount"]').each(function() {
amount.push(this.value);
});
var p_id = $('#p_id').val();
var pres_id = $('#pres_id').val();
var description=$('#description').val();
var valid;
valid = validateContact();
if (valid) {
swal({
title: "Are you sure?",
text: "You wanna proceed this Payment!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-success",
confirmButtonText: "Yes, Proceed It!",
closeOnConfirm: false
},
function(isConfirm){
if (!isConfirm) return;
$.ajax({
url: "testquery/test_payments.php", // Url to which the request is send
method: "POST", // Type of request to be send, called as method
data: {
'test_id': test_id,
'amount': amount,
'p_id': p_id,
'pres_id': pres_id,
'description':description
},
success: function (data) {
if (data == 'Password Changed') {
swal("Success", "Invoice has been Generated :)", "success");
} else {
swal("Sorry", "Something Went Wrong. Please try again later:(", "error");
}
},
error: function (data) {
//other errors that we didn't handle
swal("Sorry", "Failed to Proceed. Please try later :(", "error");
}
});
});
};
// check validations
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
if (!$("#test_id").val()) {
$("#test_id_info").html("(Required)");
$("#test_id").css('background-color', '#FFFFDF');
valid = false;
}
return valid;
}
});
I want to check the test_id textbox is empty. Before dynamically generating the textboxes there, already there is a row of textboxes including test_id textbox. My problem is, before generated, it check the textbox as empty or not by using function, but after generated it does not check. I don't know where I went wrong.
Please help me may highly appreciated.
Rather than using the elementID use class name to get the collection of elements and iterate through them. the problem we have here is all input have the same id so jquery will return the first element it finds and ignore the rest since with ID we assume that it is unique throughout the DOM
function checkname(el){
}
$(document).ready(function(){
var count=0;
$(document).on('click','#add',function() {
debugger;
count++;
var html= '';
html += '<tr id="trrows">';
html += '<td id="testid"> <input id="test_id" class="form-control test_id" type="text" style="width:200px" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);" onblur="sum(this);" onkeyup="sum(this);" onchange="sum(this);"> </td>';
html += '<td id="testname"> <input id="test_name" type="text" style="width:300px" class="form-control test_name" readonly="" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>';
html += '<td id="amounts"> <input id="amount" name="amount" type="text" style="min-width:150px" class="form-control amount" readonly="" > </td>';
html += '<td><center> <i class="fa fa-trash-o"></i></center> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click','.remove',function() {
$(this).closest("#trrows").remove();
});
});
// generate bill
$(document).on('click', '#pay', function () {
var test_id = new Array();
$('input[id="test_id"]').each(function() {
test_id.push(this.value);
});
var amount = new Array();
$('input[name="amount"]').each(function() {
amount.push(this.value);
});
var p_id = $('#p_id').val();
var pres_id = $('#pres_id').val();
var description=$('#description').val();
var valid;
valid = validateContact();
if (valid) {
alert('invoice generated')
};
// check validations
function validateContact() {
debugger;
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
//list of test_id inputs
var testIdList =
document.getElementsByClassName('test_id')
for(let i= 0 ; i<testIdList.length; i++){
if (!testIdList.item(i).value) {
$("#test_id_info").html("(Required)");
$("#test_id").css('background-color', '#FFFFDF');
valid = false;
}
}
return valid;
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control test_id" type="text" style="width:200px" id="test_id" onblur="checkname(this);" onkeyup="checkname(this);" onchange="checkname(this);"> </td>
<td> <input type="text" style="width:300px" class="form-control test_name" readonly="" id="test_name" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"></td>
<td> <input type="text" style="min-width:100px" class="form-control amount" name="amount" readonly=""> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
<span id="test_id_info" class="info text-danger"></span>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Other Information</label>
<textarea class="form-control" id="description"></textarea>
</div>
</div>
</div>
<div class="text-center m-t-20">
<input type="button" class="btn btn-primary submit-btn" name="pay"value="Generate Invoice" id="pay">
</div>
</form>
Use class, name or other attributes instead id, because you have a several elements with the same ids - it's always create problems. If you need check inputs with class "text_id" before submit try to change validation function
function validateContact() {
var valid = true;
$(".demoInputBox").css('background-color', '');
$(".info").html('');
$('.text_id').map(function(i, el){
if(!$(el).val() || $(el).val().trim() == '') {
valid = false;
$("#test_id_info").html("(Required)");
$(el).css('background-color', '#FFFFDF');
}
});
return valid;
}

unable to add dynamic rows in table - javascript

I am trying to build a sort of dynamic table.
Basically, I want user to input some fields and on "Add Row" button, these inputs entered by user will populate the table below and so on, he can enter as many rows he needs. and then extract data from table rows and call service to upload.
What I have done is that I have successfully created the adding row functionality. BUT there is a input in which user selects image and then click ADD ROW button, the issue is image replaced by the previous image on all rows.
var inc = 1;
function add(tableID) {
console.log(inc);
var educationInstitute = $("#educationInstitute").val();
var educationQualification = $('#educationQualification').find(":selected").val();
var educationAdmDate = $("#educationAdmDate").val();
var educationGraDate = $("#educationGraDate").val();
//previewImage("educationImage", inc);
//var educationImage = $("#educationImage").val();
var fullPath = document.getElementById('educationImage').value;
if (fullPath) {
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
}
filename.replace(/ /g, '');
filename = filename.slice(0, -4);
alert(filename);
previewImage("educationImage", filename);
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + educationInstitute + "</td><td>" + educationQualification + "</td><td>" +
educationAdmDate + "</td><td>" + educationGraDate + "</td><td><img class='previewImage" + filename + "' src='' /></td></tr>";
$("#educationTable tbody").append(markup);
}
function del(row) {
$("table tbody").find('input[name="record"]').each(function() {
if ($(this).is(":checked")) {
$(this).parents("tr").remove();
}
});
}
function previewImage(id, filename) {
if (document.getElementById(id).files[0]) {
console.log("ID");
var reader = new FileReader();
reader.onload = function(e) {
//console.log(e.target.result);
$('.previewImage' + filename).attr('src', e.target.result);
inc += 1;
console.log(inc);
}
reader.readAsDataURL(document.getElementById(id).files[0]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset style="min-height:100px;">
<legend>Education Details </legend>
<div class="row">
<button onclick="add('educationTable')">Add Table</button>
</div>
<div class="row">
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control" name="educationInstitute" id="educationInstitute" placeholder="Institue Name" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<select class="form-control" name="educationQualification" id="educationQualification">
<option value="5">--- Qualification ---</option>
<option value="5">Option 1</option>
<option value="6">Option 2</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control datepicker" name="educationAdmDate" id="educationAdmDate" placeholder="Admission Date" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control datepicker" name="educationGraDate" id="educationGraDate" placeholder="Graduation Date" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="file" class="form-control imageFileinput" name="educationImage" id="educationImage" data-show-preview="false" />
</div>
</div>
<table class="table table-responsive table-bordered order-list" id="educationTable">
<thead>
<tr>
<th>Check</th>
<th>Institute Name</th>
<th>Qualification</th>
<th>Admission Date</th>
<th>Graduation Date</th>
<th>Degree Scanned Image</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="row">
<i class="fa fa-plus-circle fa-2x fa-fw" style="padding-left: 15px;" onclick="AddTableRow.del('educationTable')"></i>
</div>
</fieldset>
Can anyone tell me, what's I am doing wrong here ?I have spend 2 days already on it.
Another option would be to make a copy of the input on add and append it to the row in a td this field can also be hidden and when you want to get the files you can use jquery to get all the those corresponding inputs.
var markup = `
<tr>
<td><input type='checkbox' name='record'></td>
<td> ${educationInstitute}</td>
<td> ${educationQualification}</td>
<td> ${educationAdmDate}</td>
<td> ${educationGraDate}</td>
<td class='file_holder'>
<img class='previewImage${filename}' src='' />
// append the corresponding input file here for later use
</td>
</tr>`;
$("#educationTable tbody").append(markup);
$("#educationImage").clone().appendTo("#educationTable tbody tr:last-child .file_holder");
Heres the example jsfiddle

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'))),

Clearing an input field on blur

I'm attempting to clear all inputs with the class "new" on blur, but for some reason it just won't work. I've bashed my head at the this for three hours now, which obvious point am I missing? Relevant code below.
UPDATE 2
I tried changing out the switch-case block with corresponding if blocks, and they give the expected result. This eliminates the current problem, but I don't find it to be a viable answer to the original question which is why my origianl code with switch-case doesn't work.
UPDATE 1
After some research and experimenting I've discovered that I can clear all inputs with the class "new" as long as they're not inside my switch-case block. The selector I'm testing with is $('.new'), once inside the switch-case block this gives no visible effect.
#{
ViewBag.Title = "Viser infrastruktur";
Layout = "~/Views/Shared/_SuperOfficeLayout.cshtml";
}
<table class="table table-striped compact hover row-border">
<thead>
<tr>
<th>Produsent</th>
<th>Modell</th>
<th>Serienummer</th>
<th>Firmware</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="manufacturer" placeholder="Produsent" value="" />
<input type="hidden" class="autosave new" name="id" value="" />
<input type="hidden" class="autosave new" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="model" placeholder="Modell" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="serialNumber" placeholder="Serienummer" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="firmware" placeholder="Firmware" />
</div>
</td>
</tr>
#foreach (var infrastructure in Model.Infrastructures)
{
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="manufacturer" placeholder="Produsent" value="#infrastructure.Manufacturer" />
<input type="hidden" class="autosave" name="id" value="#infrastructure.Id" />
<input type="hidden" class="autosave" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="model" placeholder="Modell" value="#infrastructure.Model" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="serialNumber" placeholder="Serienummer" value="#infrastructure.SerialNumber" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="firmware" placeholder="Firmware" value="#infrastructure.Firmware" />
</div>
</td>
</tr>
}
</tbody>
#section SpecializedScripts
{
<script type="text/javascript">
function saveSettings(element, ajaxUrl, ajaxType) {
var fields = $(element).closest('tr').children('td').children('div').children('.autosave');
var abort = false;
var ajaxData = {};
$(fields).each(function () {
abort = ($(this).val() == '' || $(this).val() == null);
backgroundColor = abort == true ? '#d9534f' : '#f9f598';
$(this).css('background-color', backgroundColor).css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
ajaxData[$(this).prop('name')] = $(this).val();
});
if (abort == true) {
return false;
}
$.ajax({
url: ajaxUrl,
type: ajaxType,
data: ajaxData
}).success(function (data, textStatus, jqXHR) {
$(fields).each(function() {
$(this).css('background-color', '#5cb85c').css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
});
switch(data.status)
{
case 'Deleted':
$(element).closest('tr').remove();
break;
case 'Added':
var tableBody = $('tbody');
var html = '<tr>';
for (var field in data.result) {
if (field == 'id' || field == 'superOfficeCustomerId')
{
html += '<input type="hidden" class="autosave" name="' + field + '" value="' + data.result[field] + '" />';
}
else {
html += '<td>'
+ '<div class="control-group">'
+ '<input type="text" class="col-md-12 autosave form-control" name="' + field + '" value="' + data.result[field] + '" />'
+ '</div>'
+ '</td>';
$('input.new[name=' + field + ']').val('');
}
}
html += '</tr>';
$(tableBody).append(html);
case 'Modified':
$(fields).each(function () {
$(this).val(data.result[$(this).prop('name')]);
});
break;
}
}).fail(function () {
});
}
$(document).on('blur', 'input.autosave', function () {
saveSettings($(this), '/Link/SaveInfrastructure', 'POST');
});
$(document).on('change', 'input.new', function () {
});
</script>
}
Something like this should work:
$('input.new').on('blur', function() { $(this).val(''); $(this).text(''); });
just make sure the input exists when you bind the event otherwise you can do:
$(document).on('blur', 'input.new', function() { $(this).val(''); $(this).text(''); });
For vanilla JavaScript, you can use
<input onBlur={(event) => { event.target.value = ''; }} />

Categories