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
Related
I am trying to be able to display data in text inputs and a select input from an existing table, that on click of an edit button (one for each row), the data is inserted. I also want it to use the this function (which I'm not confident using) so that only data from the row that is clicked on, is inputted into the text inputs. Currently the values are showing up as undefined. Sorry about the messy code.
function displayStudent(student) {
let newStudent =
`<tr>
<td>${student.firstName}</td>
<td>${student.lastName}</td>
<td>${student.grade}</td>
<td>${student.email}</td>
<td><input type="button" value="EDIT" class="editButton" onclick="editStudent(this)"></td>
</tr>`;
document.getElementById('studentTable').innerHTML += newStudent;
}
function editStudent() {
document.getElementById("firstName").value = this.document.getElementsByTagName("td")[0].value;
document.getElementById("lastName").value = this.document.getElementsByTagName("td")[1].value;
document.getElementById("grade").value = this.document.getElementsByTagName("td")[2].value;
document.getElementById("email").value = this.document.getElementsByTagName("td")[3].value;
}
<table id="studentTable">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Grade</th>
<th>Email</th>
</tr>
</table>
<div id="editFields">
<div class="fields">
<label for="firstName">First Name</label>
<input id="firstName" type="text">
</div>
<div class="fields">
<label for="lastName">Last Name</label>
<input id="lastName" type="text">
</div>
<div class="fields">
<label for="grade">Grade</label>
<select id="grade">
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<div class="fields">
<label for="email">Email</label>
<input id="email" type="text">
</div>
Please do not pass this, pass event and you can get the details of current row and fill the inputs
<td><input type="button" value="EDIT" class="editButton" onclick="editStudent(event)"></td>
function editStudent(e) {
e.preventDefault();
document.getElementById("firstName").value = e.target.parentElement.parentElement.children[0].textContent;
document.getElementById("lastName").value = e.target.parentElement.parentElement.children[1].textContent;
document.getElementById("grade").value = e.target.parentElement.parentElement.children[2].textContent;
document.getElementById("email").value = e.target.parentElement.parentElement.children[3].textContent;
}
I've prepared a more detailed example with ids being generated dynamically and button's name and "onclick" function content changing according to action.
Here also is the codepen view which I've used to edit it:
https://codepen.io/antiqtech/pen/YzZaKGJ
<table id="studentTable">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Grade</th>
<th>Email</th>
</tr>
</table>
<div id="editFields">
<div class="fields">
<label for="firstName">First
Name</label>
<input id="firstName"
type="text">
</div>
<div class="fields">
<label for="lastName">Last Name</label>
<input id="lastName" type="text">
</div>
<div class="fields">
<label for="grade">Grade</label>
<select id="grade">
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<div class="fields">
<label for="email">Email</label>
<input id="email" type="text">
</div>
<button type="button" id="btnEditUpdate"
onclick="insertStudent();">Insert</button>
function insertStudent() {
var student = { firstName: "", lastName: "", grade: "",
email: "" };
student.firstName =
document.getElementById("firstName").value;
student.lastName = document.getElementById("lastName").value;
student.grade = document.getElementById("grade").value;
student.email = document.getElementById("email").value;
displayStudent(student);
}
function displayStudent(student)
{
var cc = Math.random();
let newStudent =
`<tr>
<td id="fn_` +
cc +
`">${student.firstName}</td>
<td id="ln_` +
cc +
`">${student.lastName}</td>
<td id="gr_` +
cc +
`">${student.grade}</td>
<td id="em_` +
cc +
`">${student.email}</td>
<td><input type="button" value="EDIT"
class="editButton"
onclick="editStudent(` +
cc +
`)"></td>
</tr>`;
document.getElementById("studentTable").innerHTML +=
newStudent;
document.getElementById("firstName").value = "";
document.getElementById("lastName").value = "";
document.getElementById("grade").value = "";
document.getElementById("email").value = "";
}
function editStudent(val)
{
document.getElementById("firstName").value =
document.getElementById(
"fn_" + val).innerHTML;
document.getElementById("lastName").value =
document.getElementById(
"ln_" + val).innerHTML;
document.getElementById("grade").value =
document.getElementById(
"gr_" + val).innerHTML;
document.getElementById("email").value =
document.getElementById(
"em_" + val).innerHTML;
document.getElementById("btnEditUpdate").onclick = function
() {
updateStudent(val);
};void 0;
document.getElementById("btnEditUpdate").innerHTML =
"Update";
}
function updateStudent(val)
{
document.getElementById("fn_" + val).innerHTML =
document.getElementById(
"firstName").value;
document.getElementById("ln_" + val).innerHTML =
document.getElementById(
"lastName").value;
document.getElementById("gr_" + val).innerHTML =
document.getElementById(
"grade").value;
document.getElementById("em_" + val).innerHTML =
document.getElementById(
"email").value;
document.getElementById("firstName").value = "";
document.getElementById("lastName").value = "";
document.getElementById("grade").value = "";
document.getElementById("email").value = "";
document.getElementById("btnEditUpdate").onclick = function ()
{
insertStudent();
};
document.getElementById("btnEditUpdate").innerHTML =
"Insert";
}
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;
}
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>
I am trying to get the value from an input into a cell of a table and I do not know why the val(); is not working(not getting the value). I have checked everywhere, here, here and here but with little success. I belive my code is correct. Am I missing something about the rendering or my code is wrong? All help will be apreciated.
thank you in advance
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_studies_button");
var studies = $("#studies").val();
var x = 1; //initlal text box count
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++;
$(wrapper).append('<tr>' +
'<td>' + studies + '</td>' +
'<td>Que tal</td>' +
'<td>Pitt</td>' +
'<td>35</td>' +
'<td>New York</td>' +
'<td><a class="remove_field">Remove</a></td>' +
'</tr>');
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent().parent().remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-horizontal pull-right col-xs-6">
<div class="form-group">
<label class="col-lg-3 control-label">Studies:</label>
<div class="col-lg-8">
<input class="form-control" maxlength="100" type="text" id="studies" required="required" placeholder="Studies">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<button class="btn btn-primary pull-right add_studies_button" style="margin-top:7px;">Add</button>
<span></span>
</div>
</div>
<div class="table-responsive col-xs-6">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Studies</th>
<th>School</th>
<th>From</th>
<th>To</th>
<th>Action</th>
</tr>
</thead>
<tbody class="input_fields_wrap">
</tbody>
</table>
</div>
Try adding the statement:
var studies = $("#studies").val();
inside the click listener:
$(add_button).click(function(e) {
This is so that it gets the value of the #studies input box at the time of click. The variable studies in your code is set at the beginning and never updated (it does not automatically update to the value of #studies).
See a working example here.
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 = ''; }} />