I am trying to bind the sum of selected checkboxes from a table. I am almost there but I cannot figure out what I am doing wrong. The picture shows 2 selected boxes
you see the result of my code. I am open to suggestions if there is a better way of going about this.
$http.get('/api/Products/').success(function (data, status) { $scope.productList = data; });
$scope.selection = [];
$scope.OrderAmount = []
$scope.myTotal = 0;
$scope.toggleSelection = function toggleSelection(ProductId) {
var idx = $scope.selection.indexOf(ProductId);
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
else {
$scope.selection.push(ProductId);
}
for (var i = 0; i < $scope.selection.length; i++) {
var OrderProductId = $scope.selection[i]
var data = Enumerable.From($scope.productList).Where("x => x.ProductId == '" + OrderProductId + "'").ToArray();
$scope.OrderAmount.push(data[0].ProductPrice)
// $scope.OrderAmount = ["8500", "8500"]
for (var i = 0, len = $scope.OrderAmount.length; i < len; i++) {
$scope.myTotal += $scope.OrderAmount[i][0];
};
};
$scope.$watch('myTotal', function (value) {
$scope.model.OrderAmount = value;
});
};
view
<table class="table">
<th>Product</th>
<th>Price</th>
<tbody>
<tr ng-repeat="model in products">
<td>
<div class="toggle-switch" data-ts-color="blue">
<input id="{{model.ProductId}}" type="checkbox" hidden="hidden" ng-checked="selection.indexOf(model.ProductId) > -1" ng-click="toggleSelection(model.ProductId)">
<label for="{{model.ProductId}}" class="ts-helper"></label>
</div>
</td>
<td>{{model.ProductName}}</td>
<td>{{model.ProductPrice}}</td>
</tr>
</tbody>
</table>
<div class="form-group">
<input type="text" ng-model="model.OrderAmount" class="form-control fg-input">
</div>
UPDATE to first answer
You are doing the data binding wrongly. The checked status should be bound using ng-model but not ng-checked. You can make this easy by using an attribute (in the example checked) inside model and then loop over products to calculate the sum.
<tr ng-repeat="model in products">
<td>
<div class="toggle-switch" data-ts-color="blue">
<input id="{{model.ProductId}}" type="checkbox" hidden="hidden" ng-model="model.checked" ng-click="toggleSelection()">
<label for="{{model.ProductId}}" class="ts-helper"></label>
</div>
</td>
<td>{{model.ProductName}}</td>
<td>{{model.ProductPrice}}</td>
</tr>
Controller:
$scope.toggleSelection = function() {
var sum = 0;
angular.forEach($scope.products, function(value){
if (value.checked) sum += value.ProductPrice;
});
$scope.model.OrderAmount = sum;
}
Related
I do not understand javascript at all, I study as needed and I need help
I need to sum up the values of certain columns of a table, the rows of which are marked with a checkbox
For example: I mark the checkbox in two rows of the table and the sum of 3,4 and 5 columns is summed up and displayed somewhere on the page
Now I managed to find a piece of code that summarizes the value of the checked checkboxes in the form, and displays it on the page
I need help in replacing the part that receives the "value" of the input, with the one that gets the values of the cells in the stob = head of the table and sums them
Here is this code
var
$form = $("#out_form"),
$allCheckboxes = $("input:checkbox", $form),
$sumOut = $("#checked-sum"),
$countOut = $("#checked-count");
$allCheckboxes.change(function() {
var
sum = 0,
count = 0;
$allCheckboxes.each(function(index, el) {
var
$el = $(el),
val;
if ($el.is(":checked")) {
count++;
val = parseFloat($el.val());
if (!isNaN(val)) {
sum += val;
}
}
});
$sumOut.text(sum);
$countOut.text(count);
});
HTML
<form action="" method="post" id="out_form">
<input type="hidden" name="next" value="{{next}}"/>
<button type="submit">Check</button>
<span id="checked-sum">0</span>
<span id="checked-count">0</span>
{%csrf_token%}
<div class="table-view__container">
<table class="table-view__table">
<tbody class="table-view__body">
{% for out in filter.qs %}
<tr>
<td>
<label class="custom_Label">
<input type="checkbox" name="checked" value="{{ out.id }}">
<span class="checkmark"></span>
</label>
</td>
<td>{{out.date|date:"d(D).m.Y"}}</td>
<td>{{out.ts}}</td>
<td>{{out.pl}}</td>
<td>{{out.rem}}</td>
<td>{{out.comment}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</form>
It is necessary to sum these 3 columns:
...
<td>{{out.ts}}</td>
<td>{{out.pl}}</td>
<td>{{out.rem}}</td>
...
UPD:
I managed to display the amount with the checkbox active, but only the first line:
var
$form = $("#out_form"),
$table = $(".table-view"),
$allCheckboxes = $("input:checkbox", $form),
$sumOut = $("#checked-sum"),
$countOut = $("#checked-count");
$allCheckboxes.change(function() {
var
sum = 0,
count = 0;
$allCheckboxes.each(function(index, el) {
var
$el = $(el),
val;
if ($el.is(":checked")) {
count++;
$form.each(function () {
var val1 = parseInt(document.querySelector(".ts", this).innerHTML,10);
var val2 = parseInt(document.querySelector(".pl", this).innerHTML,10);
var val3 = parseInt(document.querySelector(".rem", this).innerHTML,10);
var total = (val1 * 1) + (val2 * 1) + (val3 * 1);
sum += total;
});
if (!isNaN(val)) {
sum += total;
}
}
});
$sumOut.text(sum);
$countOut.text(count);
});
JavaScript can be confusing, its definitely not an easy programming language. Sorry for not using your code, but I think its overcomplicating things.
So mainly what this code does is to trigger a function using event handlers on all checkboxes, that sums or substracts from the result variable depending if they are checked or unchecked and then show the result in a <span> tag.
Some key points
I used document.querySelectorAll('input[type=checkbox]') to get all the checkbox elements.
The following code is to create one event handler for each checkbox element:
boxes.forEach((box) => {
box.addEventListener("change", function() {
The input checkbox element lives inside a <td></td>, so this.closest('td').nextElementSibling is necessary to get the parent tag and then with the help of nextElementSibling we can get the next <td> element of the table which has the value we need to sum or substract.
Snippet
var boxes = document.querySelectorAll('input[type=checkbox]'),
show = document.getElementById('showResult'), result = 0;
boxes.forEach((box) => {
box.addEventListener("change", function() {
var firstElement = this.closest('td').nextElementSibling,
secondElement = firstElement.nextElementSibling,
firstValue = parseInt(firstElement.innerHTML),
secondValue = parseInt(secondElement.innerHTML);
var sum = firstValue + secondValue;
this.checked ? result += sum : result -= sum;
show.innerHTML = result;
});
});
td {
border: 1px solid #dddddd;
text-align: left;
width:50px;
text-align:center;
}
span{
font-size:20px;
}
<table id="table">
<tr>
<td><input type="checkbox" id="box1" /></td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td><input type="checkbox" id="box2" /></td>
<td>3</td>
<td>4</td>
</tr>
</table>
<br>
<br>
<span>Result: </span><span id="showResult">0</span>
So, I've been recently tasked to do a few calculations and to build a custom JS statistics library. The only 3 things I have left are to create functions for the range, variance, and standard deviation. What I'm doing here is passing my array (x) into the js functions, but they keep coming up blank. Am I doing something wrong?
function findSum(x)
{
var sum = 0;
for(i = 0; i < x.length; i++)
{
sum = sum + x[i];
}
return sum;
};
function findMean(x)
{
return findSum(x) / x.length;
};
function findMedian(x)
{
x.sort( function(a,b) {return a - b;} );
var half = Math.floor(x.length/2);
if(x.length % 2)
return x[half];
else
return (x[half-1] + x[half]) / 2.0;
}
// Ascending functions for sort
function ascNum(a, b) { return a - b; }
function clip(arg, min, max) {
return Math.max(min, Math.min(arg, max));
};
function findMode(x)
{
var arrLen = x.length;
var _arr = x.slice().sort(ascNum);
var count = 1;
var maxCount = 0;
var numMaxCount = 0;
var mode_arr = [];
var i;
for (i = 0; i < arrLen; i++) {
if (_arr[i] === _arr[i + 1]) {
count++;
} else {
if (count > maxCount) {
mode_arr = [_arr[i]];
maxCount = count;
numMaxCount = 0;
}
// are there multiple max counts
else if (count === maxCount) {
mode_arr.push(_arr[i]);
numMaxCount++;
}
// resetting count for new value in array
count = 1;
}
}
return numMaxCount === 0 ? mode_arr[0] : mode_arr;
};
function findRange(x)
{
x.sort( function (a, b) {return a-b;} );
}
function findVariance(x) {
var mean = findMean(x);
return findMean(array.map(findSum(sum)) {
return Math.pow(sum - mean, 2);
}));
},
function findStandardDeviation(x)
{
return Math.sqrt(findVariance(x));
};
The HTML code:
<html>
<head>
<h1>Statistical Calculations</h1>
<title>Calculating Stats</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='Stats.js'></script>
<script language="JavaScript">
function addNumber()
{
var input = document.getElementById('input').value;
var list = document.getElementById('list');
var option = document.createElement('OPTION');
list.options.add(option);
option.text = input;
}
function getStatistics()
{
var list = new Array();
var select = document.getElementById('list');
for(i = 0; i < select.options.length; i++)
{
list[i] = parseInt(select.options[i].text);
}
document.getElementById('summation').value =findSum(list);
document.getElementById('mean').value = findMean(list);
document.getElementById('median').value = findMedian(list);
document.getElementById('mode').value = findMode(list);
document.getElementById('variance').value = findVariance(list);
document.getElementById('standardDev').value = findStandardDeviation(list);
document.getElementById('range').value = findRange(list);
document.getElementById('max').value = findMax(list);
document.getElementById('min').value = findMin(list);
}
</script>
</head>
<body>
<table>
<tr>
<td>Input Number:</td><td><input type='text' id='input'></td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Add Number' onClick='addNumber()'></td>
</tr>
<tr>
<td colspan='2'>
<select id='list' size='5'>
</select>
</td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Calculate!' onClick='getStatistics()'></td>
</tr>
<tr>
<td>Summation:</td><td><input type='text' id='summation' readonly></td>
</tr>
<tr>
<td>Mean:</td><td><input type='text' id='mean' readonly></td>
</tr>
<tr>
<td>Median:</td><td><input type='text' id='median' readonly> </td>
</tr>
<tr>
<td>Mode:</td><td><input type='text' id='mode' readonly></td>
</tr>
<tr>
<td>Max:</td><td><input type='text' id='max' readonly></td>
</tr>
<tr>
<td>Min:</td><td><input type='text' id='min' readonly></td>
</tr>
<tr>
<td>Range:</td><td><input type='text' id='range' readonly></td>
</tr>
<tr>
<td>Variance:</td><td><input type='text' id='variance' readonly></td>
</tr>
<tr>
<td>Standard Deviation:</td><td><input type='text' id='standardDev' readonly></td>
</tr>
</table>
</body>
</html>
The last 3 seem to do absolutely nothing, and I've been bashing my head in for the last few days trying to figure it out. If anyone could help sort my functions out into working order, it'd be greatly appreciated! I'm sure that the array has been passing into the functions correctly, seeing as the first 4 functions obviously worked.
I've this HTML code:
<fieldset class="rpni-border">
<legend class="rpni-border">Model</legend>
<table id="contenedorModelos" style="" class="table table-condensed">
<tbody id="modeloBody">
<tr>
<td>
<input type="radio" value="1" id="selModelo1" name="selModelos">
</td>
<td>Harum.</td>
</tr>
<tr>
<td>
<input type="radio" value="4" id="selModelo4" name="selModelos">
</td>
<td>Pariatur ut.</td>
</tr>
<tr>
<td>
<input type="radio" value="6" id="selModelo6" name="selModelos">
</td>
<td>Tempore animi.</td>
</tr>
<tr>
<td>
<input type="radio" value="8" id="selModelo8" name="selModelos">
</td>
<td>Voluptatem.</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset class="rpni-border">
<legend class="rpni-border">Branch</legend>
<table id="contenedorMarcas" style="" class="table table-condensed">
<tbody id="marcaBody">
<tr>
<td>
<input type="radio" value="3" id="selMarca3" name="selMarcas">
</td>
<td>Ea in sequi.</td>
</tr>
<tr>
<td>
<input type="radio" value="7" id="selMarca7" name="selMarcas">
</td>
<td>Exercitationem.</td>
</tr>
<tr>
<td>
<input type="radio" value="11" id="selMarca11" name="selMarcas">
</td>
<td>Sit alias sit.</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset class="rpni-border">
<legend class="rpni-border">Manufacturer</legend>
<table id="contenedorFabricante" style="" class="table table-condensed">
<tbody id="fabricanteBody">
<tr>
<td>
<input type="checkbox" value="3">
</td>
<td>Ea in sequi.</td>
</tr>
<tr>
<td>
<input type="checkbox" value="7">
</td>
<td>Exercitationem.</td>
</tr>
<tr>
<td>
<input type="checkbox" value="11">
</td>
<td>Sit alias sit.</td>
</tr>
</tbody>
</table>
</fieldset>
<button id="create" type="button">Create</button>
<div id="ModelBranch"></div>
<button id="createM" type="button">Join Model-Branch with Manufacturer</button>
<div id="ModelBranchManufacturer"></div>
And then there is this jQuery:
$(document).ready(function () {
function modelBranchManufacturerObject(config) {
var instance = this;
// initialize class vars
instance.modelKey = config.modelKey;
instance.branchKey = config.branchKey;
instance.manufacturerKeyCollection = [];
instance.globalKey;
// globalKey = modelKey + branchKey
instance.getGlobalKey = function () {
if (!instance.globalKey) {
instance.globalKey = instance.modelKey + '-' + instance.branchKey;
}
return instance.globalKey;
}
instance.addManufacturerKeyCollection = function (manufacturerArray) {
instance.manufacturerKeyCollection = manufacturerArray;
}
}
var modelBranchManufacturerCollection = {};
function addNewRelationModelBranch(modelKey, branchKey) {
var tempModelBranchManufacturerObjectInstance = new modelBranchManufacturerObject({
modelKey: modelKey,
branchKey: branchKey
});
var globalKey = tempModelBranchManufacturerObjectInstance.getGlobalKey();
if (!modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey] = tempModelBranchManufacturerObjectInstance;
} else {
return false;
}
return tempModelBranchManufacturerObjectInstance;
}
function addNewRelationModelBranchManufacturer(globalKey, manufacturerArray) {
if (modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey].manufacturerKeyCollection = manufacturerArray;
} else {
return false;
}
return modelBranchManufacturerCollection;
}
var html = '<table><tbody id="branchModel"></tbody></table>';
$("#ModelBranch").html(html);
$("#create").on("click", function () {
var currModel = $("#modeloBody").find("input[type='radio']:checked").val(),
currBranch = $("#marcaBody").find("input[type='radio']:checked").val(),
ModelBranchObject, tr;
if (currModel && currBranch) {
ModelBranchObject = addNewRelationModelBranch(currModel, currBranch);
if (ModelBranchObject) {
tr = '<tr><td><input type="checkbox" value="' + ModelBranchObject.globalKey + '" /></td>';
tr += '<td>' + ModelBranchObject.modelKey + '-' + ModelBranchObject.branchKey + '</td></tr>';
$("#branchModel").append(tr);
}
}
});
var htmlManufacturer = '<table><tbody id="branchModelManufacturer"></tbody></table>';
$("#ModelBranchManufacturer").html(htmlManufacturer);
$("#createM").on("click", function () {
var checkedModelBranch = $("#branchModelManufacturer").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#fabricanteBody").find("input[type='checkbox']:checked"),
manufacturerColl = [],
trManufacturer,
ModelBranchManufacturerObject;
for (var j = 0; j < checkedManufacturers.length; j++) {
manufacturerColl.push(checkedManufacturers[j].value);
}
console.log(manufacturerColl);
for (var i = 0; i < checkedModelBranch.length; i++) {
ModelBranchManufacturerObject = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
console.log(ModelBranchManufacturerObject);
if (ModelBranchManufacturerObject) {
trManufacturer = '<tr><td><input type="checkbox" value="' + ModelBranchManufacturerObject.globalKey + '" /></td>';
trManufacturer += '<td>' + ModelBranchObject.modelKey + '-' + ModelBranchObject.branchKey;
for (var k = 0; k < ModelBranchObject.manufacturerKeyCollection.length; k++) {
trManufacturer += ModelBranchObject.manufacturerKeyCollection[k] + '<br/>';
}
trManufacturer += '</td></tr>';
$("#branchModelManufacturer").append(trManufacturer);
}
console.log(trManufacturer);
}
});
});
What this code does is allow to pick a model and a branch and create a non repeated pairs between them and also show the results on #modelBranch div. Also allow, I think if I'm not doing something wrong, to pick one|many choices from the results in the previous step (those on #modelBranch) and one|many Manufacturers and again create a non repeated pairs between them but in this case I can not show the results on #ModelBranchManufacturer as I should do so something is not working on my code and I was not able to find where I'm failing so certainly I need some help or advice from you. For clear a bit how the process is take a look at the following example:
Pick Model1/Branch1 and click on "Create Model/Branck Pair", this will generate a pair Model1-Branch1 as image below shows.
Pick Model1/Branch2 and click on "Create Model/Branck Pair", this will generate a pair Model1-Branch2 as image below shows.
Pick Model1/Branch1 and click on "Create Model/Branck Pair", nothing will happen since this pair was added on the (1) step and this is the right behavior to follow meaning do not allow repeated pairs
Now taking the example above you should have a table like this:
checkbox Model1-Branch1
checkbox Model1-Branch2
Following with the logic now:
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and click on "Create Model/Branck-Manufacturer Pair", this should generate something like this below:
Mark to Delete | Model/Branch | Manufacturer
----------------------------------------------------
checkbox | Model1-Branch1 | Manufacturer1
checkbox | Model1-Branch2 | Manufacturer1
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and Manufacturer2 and Manufacturer3 and click on "Create Model/Branck-Manufacturer Pair", this should generate something like this below:
Mark to Delete | Model/Branch | Manufacturer
----------------------------------------------------
checkbox | Model1-Branch1 | Manufacturer1
| | Manufacturer2
| | Manufacturer3
----------------------------------------------------
checkbox | Model1-Branch2 | Manufacturer1
| | Manufacturer2
| | Manufacturer3
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and click on "Create Model/Branck-Manufacturer Pair", nothing should happen since this pair was added on the (1) step and this is the right behavior to follow meaning do not allow repeated pairs
So, why the results from #createM on click event are not show in #ModelBranchManufacturer? Where I'm making something wrong in my code? I made this Fiddle for testing purpose
Ok, after some hours of coffee and a lot of headaches I got the solution and it's working. Maybe this code is a bit different from the main on the post since I made some changes but the idea still:
function modelBranchManufacturerObject(config) {
var instance = this;
// initialize class vars
instance.modelKey = config.modelKey;
instance.branchKey = config.branchKey;
instance.manufacturerCollection = [];
instance.modelName = config.modelName || 'Sin nombre asignado';
instance.branchName = config.branchName || 'Sin nombre asignado';
instance.globalKey;
// globalKey = modelKey + branchKey
instance.getGlobalKey = function () {
if (!instance.globalKey) {
instance.globalKey = instance.modelKey + '-' + instance.branchKey;
}
return instance.globalKey;
}
}
var modelBranchManufacturerCollection = {};
function addNewRelationModelBranch(modelKey, branchKey, modelName, branchName) {
var tempModelBranchManufacturerObjectInstance = new modelBranchManufacturerObject({
modelKey: modelKey,
branchKey: branchKey,
modelName: modelName,
branchName: branchName
});
var globalKey = tempModelBranchManufacturerObjectInstance.getGlobalKey();
if (!modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey] = tempModelBranchManufacturerObjectInstance;
} else {
return false;
}
return tempModelBranchManufacturerObjectInstance;
}
function addNewRelationModelBranchManufacturer(globalKey, manufacturerArray) {
var manufacturerCollection = modelBranchManufacturerObject.manufacturerCollection;
if (modelBranchManufacturerCollection[globalKey]) {
if (manufacturerCollection !== manufacturerArray) {
modelBranchManufacturerCollection[globalKey].manufacturerKeyCollection = manufacturerArray;
return modelBranchManufacturerCollection[globalKey];
}
} else {
return false;
}
}
$("#btnCrearParMarcaModelo").on("click", function () {
var currModel = $("#modeloBody").find("input[type='radio']:checked").val(),
currBranch = $("#marcaBody").find("input[type='radio']:checked").val(),
currModelName = $("#modeloBody").find("input[type='radio']:checked").parent().next('td').text(),
currBranchName = $("#marcaBody").find("input[type='radio']:checked").parent().next('td').text(),
ModelBranchObject, tr;
if (currModel && currBranch) {
ModelBranchObject = addNewRelationModelBranch(currModel, currBranch, currModelName, currBranchName);
if (ModelBranchObject) {
tr = '<tr><td><input type="checkbox" value="' + ModelBranchObject.globalKey + '" /></td>';
tr += '<td>' + ModelBranchObject.modelName + '-' + ModelBranchObject.branchName + '</td><td id="' + ModelBranchObject.globalKey + '"></td></tr>';
$("#parMarcaModeloFabricanteBody").append(tr);
}
}
$("#parMarcaModeloFabricante").show();
});
$("#btnAgregarSelFabricante").on("click", function () {
console.log("d");
var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
manufacturerColl = [],
modelBranchManufacturerCollection;
var j = checkedManufacturers.length, item;
while (j--) {
item = checkedManufacturers[j];
if (item.type && item.type == 'checkbox' && item.checked) {
manufacturerColl.push({
id: item.value,
name: item.parentNode.nextSibling.innerHTML
});
}
}
for (var i = 0; i < checkedModelBranch.length; i++) {
modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
if (modelBranchManufacturerCollection) {
//$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).siblings().attr("rowspan", modelBranchManufacturerCollection.manufacturerKeyCollection.length);
for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).append((modelBranchManufacturerCollection.manufacturerKeyCollection)[k].name + '<br/>');
}
}
}
});
I am currently working on javascript. In this code I have a table and a textbox. When I enter data in the textbox it should show the particular value that I typed but it doesn't search any data from the table. How do I search data in the table?I have provided the link below.
http://jsfiddle.net/SuRWn/
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr ><th> </th>
<th> </th>
<th><center> <b>COURSE CODE</b></center></th>
<th><center>COURSE NAME</center></th></tr>
</thead>
<tbody>
<tr id="rowUpdate" class="TableHeaderFooter">
<td>
<center> <input type="text" name="input" value="course" ></center>
<center> <input type="text" name="input" value="course1" ></center>
<center> <input type="text" name="input" value="course2" ></center>
</td>
<td>
<center> <input type="text" name="input" value="subject" ></center>
<center> <input type="text" name="input" value="subject1" ></center>
<center> <input type="text" name="input" value="subject2" ></center>
</td>
</tr>
</tbody>
</table >
<form action="#" method="get" onSubmit="return false;">
<label for="q">Search Here:</label><input type="text" size="30" name="q" id="q" value="" onKeyUp="doSearch();" />
</form>
<script>
function doSearch() {
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for (var i = 0; i < rows.length; i++) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if (fullname) {
if (v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1)) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
}
I would like to highlight a few things for this code:
In your code, the loop starts from 0, as table has first row as header row, it will not contain any "tr" elements. Hence your function is not working.
If we start loop from 1, you need to go through the input element to search the value. Existing approach wont work.
In case of loop starting from 1, your fullname variable will look like this:
May be you will have to modify your comparison logic by fetching the value of input fields.
Ok, here is a working version, but your algorithm is not perfect.
You can debug and fix the logic errors:
First problem:
onKeyUp="javascript:doSearch();"
JSFiddle
There was many semantical errors compare with yours, still not perfect:
(lass then 3 letters problem, and cases when it finds something)
If you type "course", it finds, but still keeps all visible (you have to fix it, it's easy.)
If you type less then 3 letters, do nothing, don't hide all.
function doSearch() {
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for (var i = 0; i < rows.length; i++) {
var fullname = rows[i].getElementsByTagName("td");
if (fullname.length > 0) {
fullname = fullname[0].innerHTML.toLowerCase();
if (fullname) {
if (v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1)) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
}
}
Is your html the way you wanted? You seem to want to create a table with rows, and then filter those rows based on the users input. The way your html is now, there is only one row.
After you fix that, I would recommend using jquery. Here is a fiddle to get you started: http://jsfiddle.net/SuRWn/11/
$(function () {
var q = $('#q'),
boxes = $('td input');
$('#q').on('keyup', function (e) {
var qterm = q.val();
if (qterm.length < 3) {
boxes.show();
} else {
boxes.each(function(i,o) {
var box = $(this);
box.toggle(box.val().indexOf(qterm) > -1);
});
}
});
});
edit: note that the fiddle is filtering your input boxes and now the rows (since there are no rows to filter)
i am writing a code to select/remove the product from display table, and when the product is selected,then product with its price mus be displayed in some other table where at the end sum total is also needed which get updated as per selected product prices
<table id="table-example" class="table">
<thead>
<tr>
<th>Cause</th>
<th>Monthly Charge</th>
</tr>
</thead>
<tbody>
<tr>
<div id="selectedServices"></div>
<td id="myDiv"></td>
</tr>
</tbody>
</table>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<table id="table-example" class="table">
<thead>
<tr>
<th>Cause</th>
<th>Monthly Charge</th>
</tr>
</thead>
<div>
<tbody>
<p>
<tr>
<td>
<input type="checkbox" onclick="ToggleBGColour(this);" />
<label>table</label>
</td>
<td>80</td>
</tr>
<tr>
<td>
<input type="checkbox" onclick="ToggleBGColour(this);" />
<label>chair</label>
</td>
<td>45</td>
</tr>
<tr>
<td>
<input type="checkbox" onclick="ToggleBGColour(this);" />
<label>set</label>
</td>
<td>10</td>
</tr>
</tbody>
</div>
</table>
script
$(function() {
$(":checkbox").change(function() {
var arr = $(":checkbox:checked").map(function() { return $(this).next().text(); }).get();
$("#myDiv").text(arr.join(','));
});
});
function ToggleBGColour(item) {
var td = $(item).parent();
if (td.is('.rowSelected'))
td.removeClass("rowSelected");
else
td.addClass("rowSelected");
}
Here is the corresponding fiddle.
Based on your comment for my other answer, this should work for you then:
$(":checkbox").change(function () {
// Toggle class of selected row
$(this).parent().toggleClass("rowSelected");
// Get all items name, sum total amount
var sum = 0;
var arr = $(":checkbox:checked").map(function () {
sum += Number($(this).parents('tr').find('td:last').text());
return $(this).parents('tr').clone();
}).get();
// Display selected items and their sum
$("#selectedServices").html(arr).find('input').remove();
$("#total").text(sum);
});
This avoids the need for creating new HTML elements in the JavaScript code, and reduces the number of .maps() and .each() loops to one.
http://jsfiddle.net/samliew/uF2Ba/
Here is the javascript for but u need to remove onClick attrs :
$(function() {
$(":checkbox").change(function() {
ToggleBGColour(this);
var arr = $(":checkbox:checked").map(function() {
return $(this).next().text();
}).get();
var nums = $(":checkbox:checked").map(function() {
return parseInt($(this).parent().next().html());
}).get();
var total = 0;
for (var i = 0; i < nums.length; i++) {
total += nums[i] << 0;
}
$("#myDiv").text(arr.join(',') + 'total : '+total);
});
});
function ToggleBGColour(item) {
var td = $(item).parent();
if (td.is('.rowSelected'))
td.removeClass("rowSelected");
else
td.addClass("rowSelected");
}
I updated your fiddle with my answer : http://jsfiddle.net/A2SKr/9/
Here's what i've changed.
Slightly better formatted.
i removed the onclick attribute. Its bad practice to use this because of performance issues. Use delegates
Ive also changed a lil bit of your HTML. the output is now a table
added a total element to the output as well
javascript code :
$(":checkbox").change(function () {
var total = 0;
var check = $(":checkbox:checked");
var causes = check.map(function () {
return $(this).next().text();
}).get();
var costs = check.map(function () {
return $(this).parent().next().text()
}).get();
var tbody = $("#table-example tbody").empty();
$.each(causes, function (i, cause) {
tbody.append("<tr><td>" + cause + "</td><td id='" + i + "'><td/></tr>");
});
$.each(costs, function (i, cost) {
$('#' + i + '').html(cost);
total += parseInt(cost, 10);
});
tbody.append("<tr><td>Total</td><td>" + total + "<td/></tr>");
});
});