Dynamically pass input text in a html table to Javascript function - javascript

I am generating html table like below:
var tablebody = "";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "mCatchmentMapping.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
var struct = "<div class='message_list'><div class='module_content'>";
for (var i = 0; i < data.d.length; i++) {
tablebody = tablebody + "<div class='message'><table id='tblhtml' width='100%'><tr><td width='25%'>" + data.d[i].Name + "</td>";
tablebody = tablebody + "<td><input type='hidden' style='color: green;' id='txtCode' name='Code' size='5' type='number' value=" + data.d[i].Code + "></td>";
tablebody = tablebody + "<td width='15%' class='nr' align='left' style='color:green'><input type='text' class='nr' style='color: green;' id='txtCatchment' name='txtCatchment' size='5' type='number' value=" + data.d[i].Catchment + "></td>";
tablebody = tablebody + "<td width='15%' align='left' style='color:green'><input type='text' style='color: green;' id='txtSalesMonth1' name='SalesMonth1' size='5' type='number' value=" + data.d[i].salesMonth1 + "></td>";
tablebody = tablebody + "<td width='15%' align='left' style='color:green'><input type='text' style='color: green;' id='txtSalesMonth2' name='SalesMonth2' size='5' type='number' value=" + data.d[i].salesMonth2 + "></td>";
tablebody = tablebody + "<td width='15%' align='left' style='color:green'><input type='text' style='color: green;' id='txtSalesMonth3' name='SalesMonth3' size='5' type='number' value=" + data.d[i].salesMonth3 + "></td>";
tablebody = tablebody + "<td width='15%' align='left' style='color:green'><input type='submit' class='use-address' id='btnSave' name='Save' onclick='saveData( " + data.d[i].Code + "," + $('#txtCatchment').val() + "," + $('#txtSalesMonth1').val() + "," + $('#txtSalesMonth2').val() + "," + $('#txtSalesMonth3').val() + ")'; value='Save'/></td></tr></table></div>";
}
tablebody = tablebody + "</div></div>"
tablebody = struct + tablebody;
$("#tbDetails").append(tablebody);
},
error: function (result) {
alert("Error");
}
});
Each row which has a save button at the last td. If I click "Save" button, the corresponding rows input text value should be passed as parameters to the JavaScript function "saveData".
This is my javascript function:
function saveData(code, catchment, month1, month2, month3) {
alert("storename :" + code);
alert("catchment :" + catchment);
alert("month1 :" + month1);
alert("month2 :" + month2);
alert("month3 :" + month3);
}
when I click save, I am getting undefined value for "catchment", "month1", "month2" and "month3".
How to pass the input text value to the javascript function?

You are creating text boxes dynamically so they will not be available while creation but will be available on run time, so you have to pass them like this
tablebody = tablebody + "<td width='15%' align='left' style='color:green'><input type='submit' class='use-address' id='btnSave' name='Save' onclick='saveData( " + data.d[i].Code + ",$(\"#txtCatchment\").val(), $(\"#txtSalesMonth1\").val(),$(\"#txtSalesMonth2\").val(), $(\"#txtSalesMonth3\").val())'; value='Save'/></td></tr></table></div>";
Here is the similar example
https://jsfiddle.net/h553jzmb/

Instead using $('#txtCatchment').val use the data.d[i].Catchment and so on. Because #txtCatchment won't be unique after your loop
Modify you last line with save function with the below code.
tablebody = tablebody + "<td width='15%' align='left' style='color:green'><input type='submit' class='use-address' id='btnSave' name='Save' onclick='saveData( " + data.d[i].Code + "," + data.d[i].Catchment + "," + data.d[i].salesMonth1 + "," + data.d[i].salesMonth2 + "," + data.d[i].salesMonth3 + ")'; value='Save'/></td></tr></table></div>";
Working live example
https://jsbin.com/jayaki/edit?html,js,output
Hope this helps. Thanks !

Related

How to dispaly display() without deleting the other HTML

var students = [
["test", "test", "test"],
["test", "test", "test"]
];
students.sort();
function display() {
for (i = 1; i < students.length + 1; i++) {
document.write("<tr>");
document.write("<td>" + (i) + "</td>");
document.write("<td>" + students[i - 1][0] + "</td>");
document.write("<td>" + students[i - 1][1] + "</td>");
document.write("<td>" + students[i - 1][2] + "</td>");
document.write("<td><input type='number' class='form-control' id='quiz" + i + "' ></td>");
document.write("<td><input type='number' class='form-control' id='reqt" + i + "'></td>");
document.write("<td><input type='number' class='form-control' id='exam" + i + "'></td>");
document.write("<td><input type='number' class='form-control' id='pg" + i + "' readonly></td>");
document.write("</tr>");
}
}
function AddData() {
var AddName;
var AddCourse;
var AddBDay;
var Data;
AddName = document.getElementById('Addname').value;
AddCourse = document.getElementById('AddCourse').value;
AddBDay = document.getElementById('AddBDay').value;
if (AddName != "" && AddCourse != "" && AddBDay != "") {
Data = [AddName, AddCourse, AddBDay];
students.push(Data);
console.log(students);
display();
} else {
alert("Invalid Input");
}
}
document.write is very very old-school and it's very rarely used any more for many reasons.
You can either create a string variable that you can then add (concatenate) new strings to, or you can use more modern methods like in the example below which uses map to iterate over the array to create a new array of strings, and then join that array up into one HTML string.
const students = [
["test", "test", "test"],
["test", "test", "test"]
];
function getHtml(students) {
return students.map(arr => {
return `
<tr>
<td>${arr[0]}</td>
<td>${arr[1]}</td>
<td>${arr[2]}</td>
</tr>
`
}).join('');
}
const table = document.querySelector('table');
table.innerHTML = getHtml(students);
<table></table>
You haven't posted any HTML, but assuming you have a <table id="x"> or <tbody id="x">, modify the display function as below:
function display() {
let html = '';
students.map((item, i) => {
html += "<tr>";
html += "<td>" + (i+1) + "</td>";
html += "<td>" + item[0] + "</td>";
html += "<td>" + item[1] + "</td>";
html += "<td>" + item[2] + "</td>";
html += "<td><input type='number' class='form-control' id='quiz" + i + "' ></td>";
html += "<td><input type='number' class='form-control' id='reqt" + i + "'></td>";
html += "<td><input type='number' class='form-control' id='exam" + i + "'></td>";
html += "<td><input type='number' class='form-control' id='pg" + i + "' readonly></td>";
html += "</tr>";
});
document.getElementById("x").innerHTML = html;
}
Also, document.write is rarely to never used. More here.
element.innerHTML is generally used when you want to perform some DOM manipulation as a result of an API call or any other event, as in your case.

How to create multidimensional array using input text dynamically in javascript

I have a form that adds a row to a table dynamically and I want to save the data table. My question is how to create a multidimensional array in javascript? I try this (view)
$( "#quot tbody" ).append(
"<tr>" +
"<td>" + supplier.val()+ "<input type='hidden' id='_supplier' name='data[][supplier]' value='"+ supplier.val() + "' class='form-control'> " + "</td>" +
"<td>" + quots_number.val()+ "<input type='hidden' id='_quots_number' name='data[][quots_number]' value='"+ quots_number.val() + "'class='form-control'> " + "</td>" +
"<td>" + quots_date.val()+ "<input type='hidden' id='_quots_date' name='data[][quots_date]' value='"+ quots_date.val() + "'class='form-control'> " + "</td>" +
"<td>" + t_item_id.val()+ "<input type='hidden' id='_item_id' name='data[][item_id]' value='"+ t_item_id.val() + "'class='form-control'> " + "</td>" +
"<td>" + qty.val()+ "<input type='hidden' id='_qty' name='data[][qty]' value='"+ qty.val() + "'class='form-control'> " + "</td>" +
"<td>" + price.val()+ "<input type='hidden' id='_price' name='data[][price]' value='"+ price.val() + "'class='form-control'> "+ "</td>" +
"<td>" + currency.val()+ "<input type='hidden' id='_currency' name='data[][currency]' value='"+ currency.val() + "'class='form-control'> "+ "</td>" +
"<td>" + loc_id.val()+ "<input type='hidden' id='_loc_id' name='data[][location]' value='"+ loc_id.val() + "'class='form-control'> " + "</td>" +
"<td>" + khs_+ "<input type='hidden' id='_khs' name='data[][khs]' value='"+ khs_ + "'class='form-control'> "+ "</td>" +
"<td>" + util_+ "<input type='hidden' id='_util' name='data[][utilization]' value='"+ util_ + "'class='form-control'> "+ "</td>" +
"<td style='text-align:center;'>" +"<i onclick='removerow(this)'><span style='cursor:pointer' class='glyphicon glyphicon-remove'></span></i>"+ "</td>" +
"</tr>"
);
but after submit, it return null value.
this is my controller
if (! $_POST) {
$dataquot = (object) $this->quot->default_value;
} else { $table= $this->input->post('data');
for($i = 0; $i < count($table); $i++){
$dataquot[$i]['supplier'] = $table[$i]['supplier'];
$dataquot[$i]['quots_number'] = $table[$i]['quots_number'];
$dataquot[$i]['quots_date'] = $table[$i]['quots_date'];
$dataquot[$i]['t_item_id'] = $table[$i]['t_item_id'];
$dataquot[$i]['qty'] = $table[$i]['qty'];
$dataquot[$i]['price'] = $table[$i]['price'];
$dataquot[$i]['currency'] = $table[$i]['currency'];
$dataquot[$i]['location'] = $table[$i]['location'];
$dataquot[$i]['khs'] = $table[$i]['khs'];
$dataquot[$i]['utilization'] = $table[$i]['utilization'];
}
}
var_dump($dataquot);
array(1) { [0]=> array(10) { ["supplier"]=> NULL ["quots_number"]=> NULL ["quots_date"]=> NULL ["t_item_id"]=> NULL ["qty"]=> NULL ["price"]=> NULL ["currency"]=> NULL ["location"]=> NULL ["khs"]=> NULL ["utilization"]=> NULL } }
Thanks in advance for your kindness

Dynamic id does not work after removing row from table

I have a table with feeSetting id.It contain dynamic data , I can add and remove remove rows to table. I generated ids dynamically that work fine until user remove a rows and add again new row it override the unique id of last row. I want table to generate unique id with dynamic add and remove functionality . My code for adding row is as follow.
<tablen id="feeSetting ">
<tbody>
</tbody>
</table>
<script>
function AddRow() {
debugger;
var index = 0;
if ($("#feeSetting tbody tr").length > 0) {
index = $("#feeSetting tbody tr").length;
}
$("#feeSetting tbody").append("<tr class='gradeX'>"
+ "<td class='col-md-3'><input type='text' value='' class='form-control validate[required,custom[number]] text-input txtFromDay' id='eFromDay'/></td>"
+ "<td class='col-md-3'><input type='text' class='form-control validate[required,custom[number],min[1]] text-input txtValue' value='' id='eValue-" + index + "'/></td>"
+ "<td class='col-md-4'>"
+ "<div id='loadTypes-" + index + "' class='typeValidation'></div></td>"
+ "<td class='col-md-2'><input type='button' class='btn btn-danger btn-sm' value=' Remove '/></td>"
+ "</tr>");
renderPartialInDiv('#Url.Action("GetValidationTypeDropDown", "FeeFineSetting")?strDDName=eValidationTypeList-' + index + '&intDDID=0&intValidationID=1', '#loadTypes-' + index);
$('#eValidationTypeList-'+index).select2();
};
</script>
Try using one global variable which will increment its value on addition of each new row, see below code
<tablen id="feeSetting ">
<tbody>
</tbody>
</table>
<script>
//keep this variable outside function and use it as global variable.
var index = 0;
function AddRow() {
debugger;
index++;
$("#feeSetting tbody").append("<tr class='gradeX'>"
+ "<td class='col-md-3'><input type='text' value='' class='form-control validate[required,custom[number]] text-input txtFromDay' id='eFromDay'/></td>"
+ "<td class='col-md-3'><input type='text' class='form-control validate[required,custom[number],min[1]] text-input txtValue' value='' id='eValue-" + index + "'/></td>"
+ "<td class='col-md-4'>"
+ "<div id='loadTypes-" + index + "' class='typeValidation'></div></td>"
+ "<td class='col-md-2'><input type='button' class='btn btn-danger btn-sm' value=' Remove '/></td>"
+ "</tr>");
renderPartialInDiv('#Url.Action("GetValidationTypeDropDown", "FeeFineSetting")?strDDName=eValidationTypeList-' + index + '&intDDID=0&intValidationID=1', '#loadTypes-' + index);
$('#eValidationTypeList-'+index).select2();
};
</script>

AngularJS: function not defined error when html is generated from Javascript

I amd dynamically generating my edit table from javaScript. But function mentioned via it are not recognaizeable from AngularJS, for that, I am not able to remove and edit my rows.
Here HvacStandards() and checkemail() and showInvite() are only working. for other's i am getting following exception in chorom console:
Errors:
Uncaught ReferenceError: editRow is not defined
Uncaught ReferenceError: deleteRow is not defined
AngularJs code
$scope.HvacStandards = function () {
var rowID = $scope.newRow;
if ($scope.currentRow > 0) {
saveEdits();
} else {
var teamName = $("#teamName").val();
var email = $("#email").val();
var sHtml = "<tr id='row"+rowID+"'>"
+ "<td id=\"tno" + rowID + "\">" + rowID
+ "</td>"
+ "<td id=\"tName" + rowID + "\">" + teamName
+ "</td>" + "<td id=\"mail" + rowID + "\">" + email
+ "</td>" + "<td><button onclick='editRow(" + rowID
+ ")'>Edit</button> " + "<button onclick='deleteRow("
+ rowID + ")'>Delete</button>" + "</tr>";
$("#inviteTable").append(sHtml);
$scope.newRow++;
$("#teamName,#email").val("");
$scope.emails[$scope.number]=$scope.formData.email;
}
};
$scope.editRow = function(rowID) {
$('#teamName').val($('#tName' + rowID).html());
$('#email').val($('#mail' + rowID).html());
$scope.currentRow = rowID;
};
$scope.saveEdits = function (){
$('#teamName' + currentRow).html($('#tName').val());
$('#email' + currentRow).html($('#mail').val());
$("#teamName,#email").val("");
$scope.currentRow = -1;
};
$scope.deleteRow = function (rowID) {
$('#row' + rowID).remove();
};
$scope.showInvite = function(){
$scope.show = true;
$scope.formData = {};
};
and my html is like following:
<div name="showInviteDiv" id="showInviteDiv">
<a ng-click="showInvite()" ng-show="!show">Invite a Team</a>
</div>
<div class="invite-form" name="inviteTeamDiv" id="inviteTeamDiv" ng-show="show">
<form ng-submit="HvacStandards()" novalidate class="css-form"
name='inviteTeamsForm'>
<div>
<input type="text" name="teamName" ng-model="formData.teamName" id="teamName"
placeholder="Team Name" style="width: 38%;" required="required"
ng-minlength="6" ng-maxlength="30">
<input
type="text" name="email" ng-model="formData.email" id="email"
placeholder="Email" style="width: 38%;" required="required"
ng-pattern="/^[a-z]+[a-z0-9._]+#[a-z]+\.[a-z.]{2,5}$/" ng-change="checkEmail(form Data.email)" ng-blur="checkEmail(formData.email)">
</div>
<div>
<input type="submit" value="Invite Team"
ng-disabled="inviteTeamsForm.$invalid || isEmailExists"> or <a ng-click="hideInvite()">I'm done sending invites</a>
</div>
In the Table that you are creating, you used onclick instead of ng-click. You need to use ng-click in order to use scope function.
So your HvacStandards function will look like this:
$scope.HvacStandards = function () {
var rowID = $scope.newRow;
if ($scope.currentRow > 0) {
saveEdits();
} else {
var teamName = $("#teamName").val();
var email = $("#email").val();
var sHtml = "<tr id='row"+rowID+"'>"
+ "<td id=\"tno" + rowID + "\">" + rowID
+ "</td>"
+ "<td id=\"tName" + rowID + "\">" + teamName
+ "</td>" + "<td id=\"mail" + rowID + "\">" + email
+ "</td>" + "<td><button ng-click='editRow(" + rowID
+ ")'>Edit</button> " + "<button ng-click='deleteRow("
+ rowID + ")'>Delete</button>" + "</tr>";
$("#inviteTable").append(sHtml);
$scope.newRow++;
$("#teamName,#email").val("");
$scope.emails[$scope.number]=$scope.formData.email;
}
};
$scope.HvacStandards = function () {
var rowID = $scope.newRow;
if ($scope.currentRow > 0) {
saveEdits();
} else {
var teamName = $("#teamName").val();
var email = $("#email").val();
var sHtml = "<tr id='row"+rowID+"'>"
+ "<td id=\"tno" + rowID + "\">" + rowID
+ "</td>"
+ "<td id=\"tName" + rowID + "\">" + teamName
+ "</td>" + "<td id=\"mail" + rowID + "\">" + email
+ "</td>" + "<td><button ng-click='editRow(" + rowID
+ ")'>Edit</button> " + "<button ng-click='deleteRow("
+ rowID + ")'>Delete</button>" + "</tr>";
//$("#inviteTable").append(sHtml); // don't do this
// use compile in following manner
$("#inviteTable").append(
$compile(sHtml)($scope)
);
$scope.newRow++;
$("#teamName,#email").val("");
$scope.emails[$scope.number]=$scope.formData.email;
}
};
try this
$scope.HvacStandards = function () {
var rowID = $scope.newRow;
if ($scope.currentRow > 0) {
saveEdits();
} else {
var teamName = $("#teamName").val();
var email = $("#email").val();
var sHtml = "<tr id='row"+rowID+"'>"
+ "<td id=\"tno" + rowID + "\">" + rowID
+ "</td>"
+ "<td id=\"tName" + rowID + "\">" + teamName
+ "</td>" + "<td id=\"mail" + rowID + "\">" + email
+ "</td>" + "<td><button ng-click='editRow(" + rowID
+ ")'>Edit</button> " + "<button ng-click='deleteRow("
+ rowID + ")'>Delete</button>" + "</tr>";
// $compile(sHtml)($scope) aissign to variable:
let shown = $compile(sHtml)($scope);
$("#inviteTable").append(
shown;
);
$scope.newRow++;
$("#teamName,#email").val("");
$scope.emails[$scope.number]=$scope.formData.email;
}
};

why this javascript function is not executing, no error in console

This function is a problem:
function addInvoiceItemValue(name,pkwiu,netto,unit,qty,vat) {
if(vat == '23') v23 = " selected='selected'";
if(vat == '22') v22 = " selected='selected'";
if(vat == '8') v8 = " selected='selected'";
if(vat == '7') v7 = " selected='selected'";
if(vat == '5') v5 = " selected='selected'";
if(vat == '3') v3 = " selected='selected'";
if(vat == '0') v0 = " selected='selected'";
if(vat == 'zw') vzw = " selected='selected'";
var vatSelect = "<option value='23'"+v23+">23%</option><option value='22'"+v22+">22%</option><option value='8'"+v8+">8%</option><option value='7'"+v7+">7%</option><option value='5'"+v5+">5%</option><option value='3'"+v3+">3%</option><option value='0'"+v0+">0%</option><option value='zw'"+vzw+">zw.</option>";
var row = "<tr id='item" + itemID + "'><td><input size='30' maxlength='300' id='ii-name-" + itemID + "' name='ii-name-" + itemID + "' value='" + name + "'></td>";
row += "<td><input size='6' maxlength='50' id='ii-pkwiu-" + itemID + "' name='ii-pkwiu-" + itemID + "' value='"+pkwiu+"'></td>";
row += "<td><input size='6' maxlength='16' id='ii-netto-" + itemID + "' name='ii-netto-" + itemID + "' value='"+netto+"'></td>";
row += "<td><input size='5' maxlength='128' id='ii-unit-" + itemID + "' name='ii-unit-" + itemID + "' value='"+unit+"'></td>";
row += "<td><input size='5' maxlength='6' id='ii-qty-" + itemID + "' name='ii-qty-" + itemID + "' value='"+qty+"'></td>";
row += "<td><select id='ii-vat-" + itemID + "' name='ii-vat-" + itemID + "'>" + vatSelect + "</select></td>";
row += "<td><a onclick='delInvoiceItem(\"item" + itemID + "\")'><b>-</b> Usuń</a></td></tr>";
$('#invoiceItems tr:last').after(row);
itemID++;
}
Example execution:
addInvoiceItemValue('yyy','','676.76','','1','23');
addInvoiceItemValue('fgh','','777.00','','1','8');
And here is function that work's fine:
function addInvoiceItem() {
var vatSelect = "<option value='23'>23%</option><option value='22'>22%</option><option value='8'>8%</option><option value='7'>7%</option><option value='5'>5%</option><option value='3'>3%</option><option value='0'>0%</option><option value='zw'>zw.</option>";
var row = "<tr id='item" + itemID + "'><td><input size='30' maxlength='300' id='ii-name-" + itemID + "' name='ii-name-" + itemID + "' value=''></td>";
row += "<td><input size='6' maxlength='50' id='ii-pkwiu-" + itemID + "' name='ii-pkwiu-" + itemID + "' value=''></td>";
row += "<td><input size='6' maxlength='16' id='ii-netto-" + itemID + "' name='ii-netto-" + itemID + "' value='0'></td>";
row += "<td><input size='5' maxlength='128' id='ii-unit-" + itemID + "' name='ii-unit-" + itemID + "' value=''></td>";
row += "<td><input size='5' maxlength='6' id='ii-qty-" + itemID + "' name='ii-qty-" + itemID + "' value='1'></td>";
row += "<td><select id='ii-vat-" + itemID + "' name='ii-vat-" + itemID + "'>" + vatSelect + "</select></td>";
row += "<td><a onclick='delInvoiceItem(\"item" + itemID + "\")'><b>-</b> Usuń</a></td></tr>";
$('#invoiceItems tr:last').after(row);
itemID++;
}
The v23, v22, v8, v7, v5, v3, v0, vzw and itemdID are not always defined in all code paths.
This causes the script to fail.
You should change your function to
function addInvoiceItemValue(name,pkwiu,netto,unit,qty,vat) {
var vats = ['23','22','8','7','5','3','0','zw'];
var vatSelect = '';
for (var i = 0; i < vats.length; i++)
{
vatSelect += '<option value="'+vats[i]+'"';
if (vat == vats[i])
vatSelect += ' selected="selected"';
vatSelect += '>'+vats[i] + '%</option>';
}
var row = "<tr id='item" + itemID + "'><td><input size='30' maxlength='300' id='ii-name-" + itemID + "' name='ii-name-" + itemID + "' value='" + name + "'></td>";
row += "<td><input size='6' maxlength='50' id='ii-pkwiu-" + itemID + "' name='ii-pkwiu-" + itemID + "' value='"+pkwiu+"'></td>";
row += "<td><input size='6' maxlength='16' id='ii-netto-" + itemID + "' name='ii-netto-" + itemID + "' value='"+netto+"'></td>";
row += "<td><input size='5' maxlength='128' id='ii-unit-" + itemID + "' name='ii-unit-" + itemID + "' value='"+unit+"'></td>";
row += "<td><input size='5' maxlength='6' id='ii-qty-" + itemID + "' name='ii-qty-" + itemID + "' value='"+qty+"'></td>";
row += "<td><select id='ii-vat-" + itemID + "' name='ii-vat-" + itemID + "'>" + vatSelect + "</select></td>";
row += "<td><a onclick='delInvoiceItem(\"item" + itemID + "\")'><b>-</b> Usuń</a></td></tr>";
$('#invoiceItems tr:last').after(row);
itemID++;
}
but the itemID also has to be defined.
When is it SUPPOSED to be executing?
While this technically bad coding practice, test with this:
<a href='#' onClick="javascript: function('value');" > Click Me </a>
If you click, and it still doesn't work, it is an issue with your function. If you click and it works, the function is never being called in the first place.
You should also check your selector.
$('#invoiceItems tr:last').after(row);
Try adding it in a simpler place. Make another div,...
Then use the selector $('#result');
In any case, if your selector is bad, it will never execute and it won't throw an error b/c it never had cause to do what you told it. Now that I think about it, I think this is the issue.
Do me a favor and try
$('#invoiceItems tr:last').each(alert('exist???'));
If it doesn't alert, your selector is most likely not working. (For each thing that meets the criteria , do an alert)

Categories