Problems with creating dynamically <select/> - javascript

<script type="text/javascript">
var a = new Array();
function obj(type, value) {
this.type = type;
this.value = value;
this.toStr = toStr
}
function toStr() {
if (this.type == "select") {
var temp = "";
var arr = this.value.split("/");
for (i = 0; i < arr.length; i++) {
temp += "<option>" + arr[i] + "</option>"
}
return "<select>" + temp + "</select><br>";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "'><br>";
}
function addObj(type) {
var sel = parent.frames["left"].document.form1.q.value;
for (i = 0; i < sel; i++)
a[a.length] = new obj(type,
parent.frames["left"].document.form1.caption_text.value,
a.length);
paint();
parent.frames["left"].document.form1.caption_text.value = "";
}
function paint() {
parent.frames["right"].document.open()
for (i = 0; i < a.length; i++)
parent.frames["right"].document.writeln(a[i].toStr())
parent.frames["right"].document.close()
}
</script>
<form name=form1>
<table>
<tr>
<td><input type="button" style="width: 150px" value="Add Button" onClick="addObj('button')"><br />
<input type="button" style="width: 150px" value="Add TexBox" onClick="addObj('text')" /><br />
<input type="button" style="width: 150px" value="Add Select" onClick="addObj('select')" /></td>
<td>Text : <br /> Number of adding elements:<br /></td>
<td><input type="text" name="caption_text" style="width: 150px"> <br /> <select
NAME=q size=1 style="width: 150px">
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
</table>
</FORM>
Code is corrupting when creating select elements.
What's wrong with this code?
Thanks in advance.

Your i variables are missing a var declaration. All loops use the same counter, which means that nested loops will break horribly. My suggestion:
var a = [];
function FormElement(type, value) {
this.type = type;
this.value = value;
}
FormElement.prototype.toString = function toStr(){
if (this.type == "select") {
var arr = this.value.split("/");
for (var i = 0; i < arr.length; i++) {
arr[i] = "<option>" + arr[i] + "</option>"
}
return "<select>" + arr.join("") + "</select><br />";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "' /><br />";
};
function addObj(type) {
var form = parent.frames["left"].document.form1;
var sel = form.q.value;
for (var i = 0; i < sel; i++)
a.push(new FormElement(type, form.caption_text.value);
paint();
form.caption_text.value = "";
}
function paint() {
var doc = parent.frames["right"].document;
doc.open();
doc.write(a.join("\n"));
doc.close();
}

Related

How do I add up all numbers into one variable and show it?

Whenever I try doing the code myself, nothing shows up after I run the function, I'm wanting to add all the numbers from 'fkWynik'.
function mat_WypiszLiczbyNaturalne() {
var T = "";
T = document.getElementById('fkEdit').value;
if ((T.trim() != "") && (Number(T) > 0)) {
var S = "";
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
}
document.getElementById('fkWynik').value = S.substr(2) + " = ";
} else {
document.getElementById('fkWynik').value = "Prosze wprowadzic liczbe!";
}
}
<html>
<body>
<FORM NAME="formularz1" ACTION="">
<TABLE BORDER="0">
<INPUT TYPE="number" ID="fkEdit" STYLE="height:24px; width:55px;">
<INPUT TYPE="button" ID="fkWykonaj" VALUE="Wykonaj" onClick="mat_WypiszLiczbyNaturalne();"> </TD>
</TR>
<TR><TD> <INPUT TYPE="text" ID="fkWynik" STYLE="width:545px; height:24px;" READONLY> </TD></TR>
</TABLE>
</FORM>
</body>
</html>
You need to add the numbers together and concat it to the string:
function mat_WypiszLiczbyNaturalne() {
var T = "";
T = document.getElementById('fkEdit').value;
if ((T.trim() != "") && (Number(T) > 0)) {
var S = "";
var total = 0
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
total += I;
}
document.getElementById('fkWynik').value = S.substr(2) + " = "+total.toString();
} else {
document.getElementById('fkWynik').value = "Prosze wprowadzic liczbe!";
}
}
<html>
<body>
<FORM NAME="formularz1" ACTION="">
<TABLE BORDER="0">
<INPUT TYPE="number" ID="fkEdit" STYLE="height:24px; width:55px;">
<INPUT TYPE="button" ID="fkWykonaj" VALUE="Wykonaj" onClick="mat_WypiszLiczbyNaturalne();"> </TD>
</TR>
<TR><TD> <INPUT TYPE="text" ID="fkWynik" STYLE="width:545px; height:24px;" READONLY> </TD></TR>
</TABLE>
</FORM>
</body>
</html>
The following should work if your HTML code contains an element with the property id="fkWynik"
function mat_WypiszLiczbyNaturalne() {
var elem = document.getElementById('fkEdit');
if(!elem) {
console.error("No element with id 'fkEdit' in the page.");
return;
}
var T = elem.value;
var value = "";
if (T && !isNaN(Number(T))) { // if T not null, not empty, not undefined, not 0 and is a number
var S = "";
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
}
value = S.substr(2) + " = ";
} else {
value = "Proszę wprowadzić liczbę!";
}
console.log("value: " + value);
document.getElementById('fkWynik').value = value;
}
mat_WypiszLiczbyNaturalne();

Get all spreadsheet data to client side first, then "find row number and same row values using javascript for a specific value"

Code.js
/**
* Load Spreadsheet by ID
* Get all Sheets present in that spreadsheet
* Loop through each sheet
* Create an object with sheet's name as Key of the object
* and sheets data as Value of the object
* Return the key-value paired object
*/
function doGet(e) {
return HtmlService
.createHtmlOutputFromFile('form.html')
.setTitle("Exam Result");
}
function getAllResult()
{
var id = '1da6d8rfWgZrG2Cnpyho6YDx0C7Me4o20rM4PhDi8yCY'; // ID of the Result spreadsheet
var ss = SpreadsheetApp.openById(id);
var sheets = ss.getSheets(); // get all the sheets in the spreadsheeet
var allSheetsData = {}; // initialize javascript object
var sheetName = '';
var sheetValues;
for (i = 0; i < sheets.length; i++) {
sheetName = sheets[i].getName();
sheetValues = sheets[i].getDataRange().getValues();
allSheetsData[sheetName] = sheetValues;
}
//Logger.log(allSheetsData);
return allSheetsData;
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
window.onload = function() {
init(); // initial function to run on page load
};
// initializing object that will be storing all result data
var allResultData = {};
// loading image
var loading = '<img width="25px" ' +
'src="https://lh6.googleusercontent.com/PshQKOjKS5j6IEaEXZ6r7-JOFZwYOBopBt82Q-kTGdRcW6wi3SBHDAUHebb2yreOeTpGfzgs=w1280-h661"> ' +
'Loading...';
/**
* First function to run on page load
*/
function init() {
document.getElementById('progressClass').innerHTML = loading; // show loading image
/**
* This calls getAllResult() function of Code.gs
* The returned value from getAllResult() is passed to populateClass(value) function
* present in this html file
*/
google.script.run
.withSuccessHandler(populateClass)
.getAllResult();
}
/**
* Second function to run after init() function
* Populates the "Class" select box
*/
function populateClass(value) {
document.getElementById('progressClass').innerHTML = ''; // hide loading image
allResultData = value; // all result data is stored in allResultData object
var className = Object.keys(value);
var classes = '<option>Please Select</option>';
for (i = 0; i < className.length; i++) {
classes += "<option>" + className[i] + "</option>";
}
document.getElementById("class").innerHTML = classes;
}
function populateSymbolNumber(value)
{
{var day = "<option>Day</option>";
var data = allResultData[value]
for (i=1; i < 32; i++) { // start from i=1, skipping 1st row as it's heading
day += "<option value="+i+">" + data[i][3] + "</option>";
}
document.getElementById("day").innerHTML = day;}
{var month = "<option>Month</option>";
var data = allResultData[value]
for (i=1; i < 13; i++) { // start from i=1, skipping 1st row as it's heading
month += "<option value="+i+">" + data[i][4] + "</option>";
}
document.getElementById("month").innerHTML = month;}
{var year = "<option>Year</option>";
var data = allResultData[value]
for (i=1; i < 122; i++) { // start from i=1, skipping 1st row as it's heading
year += "<option value="+i+">" + data[i][5] + "</option>";
}
document.getElementById("year").innerHTML = year;}
{var symbol = "<option>Please Select</option>";
var data = allResultData[value]
for (i=1; i < data.length; i++) { // start from i=1, skipping 1st row as it's heading
symbol += "<option value="+i+">" + data[i][0] + "</option>";
}
document.getElementById("symbol").innerHTML = symbol;}
}
/**
* Show name of student and marks result
*/
function submitForm(value) {
var grade = document.getElementById("class");
var gradeValue = grade.options[grade.selectedIndex].value;
var classResult = allResultData[gradeValue];
var symbol = document.getElementById("symbol");
var day = document.getElementById("day");
var month = document.getElementById("month");
var year = document.getElementById("year");
var symbolText = symbol.options[symbol.selectedIndex].text;
var DayText = day.options[day.selectedIndex].text;
var MonthText = month.options[month.selectedIndex].text;
var YearText = year.options[year.selectedIndex].text;
var symbolValue = symbol.options[symbol.selectedIndex].value;
var dob = DayText + '-' + MonthText + '-' + YearText;
var marks = '';
var headerRow = classResult[0];
//console.log(headerRow);
for (i = 1; i < headerRow.length; i++) { // start from i=1, skipping 1st column as it contains symbol number
marks += headerRow[i] + ': ' + classResult[symbolValue][i] + '<br>';
}
var result = "Symbol Number: " + symbolText + '<br>' + marks;
document.getElementById('result').innerHTML = result;
return false;
}
</script>
</head>
<body>
<div id="form">
<table cellpadding="5px">
<tr>
<td>Class</td>
<td>
<select id="class" onchange="populateSymbolNumber(this.value)">
<option value="">Please Select</option>
</select>
<span id="progressClass"></span>
</td>
</tr>
<tr>
<td>Symbol</td>
<td>
<select id="day">
<option value="">Day</option>
</select>
</td>
<td>
<select id="month">
<option value="">Month</option>
</select>
</td>
<td>
<select id="year">
<option value="">Year</option>
</select>
</td>
<td>
<select id="symbol">
<option value="">Please Select</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td>
<button onclick="submitForm(); return false;">Submit</button>
</td>
</tr>
</table>
</div>
<div id="result" style="border-top: 1px solid #ccc; padding: 5px"></div>
</body>
</html>
There is a variable
var dob = DayText + '-' + MonthText + '-' + YearText;
I want to find row number for the "dob" value in the loaded data.
Google sheet has value as 30-December-1992.

JavaScript class did not function in asp.net

I have created a javascript function in my aspx page..
below are the sample code,
<script type="text/javascript">
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
</script>
I would like this function execute in the property such as
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>
As the code running, the javascript function above should be executed and display the " Choose Year" propery inside as shown above.
I try to run this code but nothing happens to the property. Any help would be appreciated. Thank u.
Your code seems to be working as below. However you may be missing the jQuery script so you can check if that exists.
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>

How to stop adding duplicate values in select list box

I'm new to java script. I want prevent adding duplicate values to fourth list box. For example, It would not be same like below i) Paper Manufacturers << Paper Converters << Molded Pulp Products ii) Paper Manufacturers << Paper Converters << Molded Pulp Products And If there is no values in the fourth box, The "Remove Category" Button should be in disabled mode. If there is values & if i select any values in 4th box, The "Remove Category" Button should be enabled & "Add Category" button should be disabled.
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#tget");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 20 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 ";
choice.text(strText);
}
function appendChoice() {
var count="";
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0) {alert('This category has already been added.');
return count=1;
}
else {
selectedList.append('<option value="'+ givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] +'">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
return count=2;
}
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
var a=appendChoice();
if(a==2){
setAvailableChoice(availableChoice - 1);
}
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function() {
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option value="1">Paper Manufacturers</option>
<option value="2">Paper Products Suppliers</option>
<option value="3">Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option value="1">Paper Converters</option>
<option value="2">Lab Apparatus & Supplies</option>
<option value="3">Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option value="1">Molded Pulp Products</option>
<option value="2">Software Vendors</option>
<option value="3">Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>
Use this script. It will show alert if try to add duplicate entry. I have changed in function appendChoice().
$(document).ready(function () {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#target");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function () {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 5 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";
choice.text(strText);
}
function appendChoice() {
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
alert('Duplicate value not allowed.');
else
selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
}
addCategoryButton.click(function () {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
appendChoice();
setAvailableChoice(availableChoice - 1);
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function () {
removeCategoryButton.prop("disabled", false);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function () {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
});
}
});
Check the working code snippet
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#target");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton(){
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton );
}
function getNumberOfSelectedOption(){
return selectedList.find("option").length;
}
function getAvailableChoice(){
return 5 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice){
var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";
choice.text(strText);
}
function appendChoice(){
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
alert('Duplicate value not allowed.');
else
selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if(availableChoice >= 1){
appendChoice();
setAvailableChoice(availableChoice - 1);
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function(){
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener(){
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if(0 < availableChoice < 6){
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option>Paper Manufacturers</option>
<option>Paper Products Suppliers</option>
<option>Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option>Paper Converters</option>
<option>Lab Apparatus & Supplies</option>
<option>Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option>Molded Pulp Products</option>
<option>Software Vendors</option>
<option>Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>

Dynamically add or delete rows in a table using jQuery

Dynamically add or delete rows in a table using jQuery but how to keep data in arrays after removing a row and don't get the totalSum when I add new row after deleting previous one .row add sucessfully and get initial sum but aftre remove operation i get NAN total sum
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
function validation() {
if (document.getElementById(txt_item).value == "")
alert("Please Enter a Item name");
return false;
if (document.getElementById(txt_price).value == "")
alert("Please Enter Price");
return false;
if (document.getElementById(txt_quantity).value == "")
alert("Please Enter Quantity");
return false;
}
</script>
<script>
var itemCount = 0;
$(document).ready(function () {
var array = [];
$("#txt_item").focus();
$("#txt_quantity").keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9) {
var table = "";
var arr = {
"Row_ID": itemCount,
"TXT_ITEM": $("#txt_item").val(),
"TXT_PRICE": $("#txt_price").val(),
"TXT_QUANTITY": $("#txt_quantity").val(),
"TOTAL_AMOUNT": $("#txt_price").val() * $("#txt_quantity").val()
}
array.push(arr);
itemCount++;
table = "<tr id='" + itemCount + "'><td>" + arr['TXT_ITEM'] + "</td><td id='price_"+itemCount+"'>" + arr['TXT_PRICE'] + "</td><td><input type='text' id='quantity_"+itemCount+"' value='" + arr['TXT_QUANTITY'] + "'></td><td id='" + itemCount + "_total'>" + parseInt(arr['TXT_PRICE']) * parseInt(arr['TXT_QUANTITY']) + "</td><td><input type='button' id='" + itemCount + "' class='btn' value='Remove'></td></tr>";
$("#test1").append(table);
totalSum();
$(".btn").click(function () {
var buttonId = $(this).attr("id");
//var value_quantity = $(this).val();
//buttonId = buttonId.replace("tr", "").trim();
//var value_price = $("#price_" + buttonId).text();
//var value_total_price = parseInt($("#"+buttonId+"_total").text());
//var tamount=parseInt($("#total_amount").text());
//$("#total_amount").text(tamount - value_total_price);
////alert(tamount);
//alert(value_total_price);
$("#" + buttonId).remove();
array.splice(buttonId - 1, 1);
//itemCount--;
totalSum();
Array_IDs();
itemCount = array.length + 1;
});
$("#quantity_" + itemCount).keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9)
var value_quantity = $(this).val();
var rowId = $(this).closest('tr').attr('id');
rowId = rowId.replace("tr", "").trim();
var value_price = $("#price_" + rowId).text();
if (value_quantity >= 0)
{
$("#" + rowId+"_total").text(value_price * value_quantity);
totalSum();
}
});
$("#txt_item").val("");
$("#txt_price").val("");
$("#txt_quantity").val("");
}
function totalSum() {
var total = 0;
var rows = array.length;
for (var i = 1; i <= rows; i++) {
total += parseInt($("#" + i + "_total").text());
//total += parseInt(array[i].TXT_PRICE * array[i].TXT_QUANTITY);
}
$("#total_amount").text(total);
//alert(total);
}
function Array_IDs()
{
for (var i = 0; i < array.length; i++) {
array[i].Row_ID = i + 1;
//alert(i);
}
//$("#test1 tr").remove();
}
});
});
</script>
</head>
<body>
<table id="test1">
<tr>
<td>Item Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total Amount</td>
<td>Action</td>
</tr>
<tfoot>
<tr>
<td><input type="text" id="txt_item" /></td>
<td><input type="text" id="txt_price" /></td>
<td><input type="text" id="txt_quantity" /></td>
<td id="total_price" align="center"></td>
</tr>
<tr>
<td></td>
<td>#*<input type="button" id="add_button" value="Add Row" />*#</td>
<td align="right">Total Amount:</td>
<td id="total_amount" align="center"></td>
</tr>
</tfoot>`enter code here`
</table>
<table id="test2" width="50%"></table>
</body>
</html>
<html>
<head>
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script>
function validation() {
if (document.getElementById(txt_item).value == "")
alert("Please Enter a Item name");
return false;
if (document.getElementById(txt_price).value == "")
alert("Please Enter Price");
return false;
if (document.getElementById(txt_quantity).value == "")
alert("Please Enter Quantity");
return false;
}
var itemCount = 0;
$(document).ready(function () {
var array = [];
$("#txt_item").focus();
$("#txt_quantity").keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9) {
var table = "";
var iPrice = 0;
if ($("#txt_price").val() == "" || isNaN($("#txt_price").val())) {
iPrice = 0;
}
else {
iPrice = parseInt($("#txt_price").val(), 10);
}
var iQuatity = 0;
if ($("#txt_quantity").val() == "" || isNaN($("#txt_quantity").val())) {
iQuatity = 0;
}
else {
iQuatity = parseInt($("#txt_quantity").val(), 10);
}
szTotal = iPrice * iQuatity;
var arr = {
"Row_ID": itemCount,
"TXT_ITEM": $("#txt_item").val(),
"TXT_PRICE": iPrice,
"TXT_QUANTITY": iQuatity,
"TOTAL_AMOUNT": szTotal
}
array.push(arr);
itemCount++;
table = "<tr id='" + itemCount + "'><td>" + arr['TXT_ITEM'] + "</td><td id='price_" + itemCount + "'>" + arr['TXT_PRICE'] + "</td><td><input type='text' id='quantity_" + itemCount + "' value='" + arr['TXT_QUANTITY'] + "'></td><td class='td_total' id='" + itemCount + "_total'>" + parseInt(arr['TXT_PRICE']) * parseInt(arr['TXT_QUANTITY']) + "</td><td><input type='button' id='" + itemCount + "' class='btn' value='Remove'></td></tr>";
$("#test1 tbody").append(table);
totalSum();
$(".btn").click(function () {
var buttonId = $(this).attr("id");
//var value_quantity = $(this).val();
//buttonId = buttonId.replace("tr", "").trim();
//var value_price = $("#price_" + buttonId).text();
//var value_total_price = parseInt($("#"+buttonId+"_total").text());
//var tamount=parseInt($("#total_amount").text());
//$("#total_amount").text(tamount - value_total_price);
////alert(tamount);
//alert(value_total_price);
$("#" + buttonId).remove();
array.splice(buttonId - 1, 1);
//itemCount--;
totalSum();
Array_IDs();
itemCount = array.length + 1;
});
$("#quantity_" + itemCount).keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9)
var value_quantity = 0;
if ($(this).val() != "" && !isNaN($(this).val()))
{
value_quantity = parseInt($(this).val(),10)
}
var rowId = $(this).closest('tr').attr('id');
rowId = rowId.replace("tr", "").trim();
var value_price = 0;
if ($("#price_" + rowId).text() != "" && !isNaN($("#price_" + rowId).text())) {
value_price=parseInt($("#price_" + rowId).text(),10);
}
if (value_quantity >= 0) {
$("#" + rowId + "_total").text(value_price * value_quantity);
totalSum();
}
});
$("#txt_item").val("");
$("#txt_price").val("");
$("#txt_quantity").val("");
}
function totalSum() {
var total = 0;
//var rows = array.length;
//for (var i = 1; i <= rows; i++) {
// total += parseInt($("#" + i + "_total").text());
// //total += parseInt(array[i].TXT_PRICE * array[i].TXT_QUANTITY);
//}
$('.td_total').each(function () {
if (!isNaN($.trim($(this).text())) && $.trim($(this).text()) != "")
{
total = total+parseInt($(this).text(),10)
}
});
$("#total_amount").text(total);
//alert(total);
}
function Array_IDs() {
for (var i = 0; i < array.length; i++) {
array[i].Row_ID = i + 1;
//alert(i);
}
//$("#test1 tr").remove();
}
});
});
</script>
</head>
<body>
<table id="test1">
<tr>
<td>Item Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total Amount</td>
<td>Action</td>
</tr>
<tbody></tbody>
<tfoot>
<tr>
<td><input type="text" id="txt_item" /></td>
<td><input type="text" id="txt_price" /></td>
<td><input type="text" id="txt_quantity" /></td>
<td id="total_price" align="center"></td>
</tr>
<tr>
<td></td>
<td>#*<input type="button" id="add_button" value="Add Row" />*#</td>
<td align="right">Total Amount:</td>
<td id="total_amount" align="center"></td>
</tr>
</tfoot>`enter code here`
</table>
<table id="test2" width="50%"></table>
</body>
</html>

Categories

Resources