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>");
});
});
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>
I have a table and I want to clone the last line of it after the [Add New] link is pressed. The table has 8 columns. When I press the [Add New] link, only the first 3 column has the same value like the one above it. The delete function is also unable to delete row.
Here is the page when it loads.
Now, I key in values for PX, Date, and Place:
Then, when i click on the [Add New] link, new row appeared below. But only 3 columns are populated:
I want the row below to clone exactly the values from the previous row.
Here's the code of the table:
<div style="width:700px; padding:5px; background-color:white;">
#using (Html.BeginForm("PxDataEntry", "PxAndTitle", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
if (ViewBag.Message != null)
{
<div style="border:solid 1px green">
#ViewBag.Message
</div>
}
<div>+ Add New</div>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<tr>
<th>PX</th>
<th>Date</th>
<th>Place</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
#if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr style="border:1px solid black">
<td>#Html.TextBoxFor(a => a[j].px)</td>
<td>#Html.TextBoxFor(a => a[j].sDate)</td>
<td>#Html.TextBoxFor(a => a[j].Place)</td>
<td>#Html.TextBoxFor(a => a[j].PId)</td>
<td>#Html.TextBoxFor(a => a[j].FId)</td>
<td>#Html.TextBoxFor(a => a[j].createdBy)</td>
<td>#Html.TextBoxFor(a => a[j].createdAt)</td>
<td>#Html.TextBoxFor(a => a[j].PxStatus)</td>
<td>
#if (j > 0)
{
Remove
}
</td>
</tr>
j++;
}
}
</table>
<input type="submit" value="Save Bulk Data" />
}
Here is the script:
#section Scripts{
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript">
$(document).ready(function () {
//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone();
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$trNew.find("td:last").html('Remove');
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
//Replaced value
var type = $(this).attr('type');
if (type.toLowerCase() == "text") {
$(this).attr('value', '');
}
// If you have another Type then replace with default value
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
// Re-assign Validation
var form = $("form")
.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
});
// 2. Remove
$('a.remove').live("click", function (e) {
e.preventDefault();
$(this).parent().parent().remove();
});
});
</script>
}
First issue is because you empty your inputs values which are cloned i.e : $(this).attr('value', ''); remove this line if you need values as well from your previous trs .Then, onclick of a tag you can simply use .closest("tr") to remove entire tr from table .
Demo Code :
$(document).ready(function() {
//1. Add new row
$("#addNew").click(function(e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone();
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$trNew.find("td:last").html('Remove');
$.each($trNew.find(':input'), function(i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
//Replaced value
var type = $(this).attr('type');
if (type.toLowerCase() == "text") {
//this line empty value of inputs
// $(this).attr('value', '');
}
// If you have another Type then replace with default value
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
})
$(document).on("click", "a.remove", function(e) {
e.preventDefault();
$(this).closest("tr").remove(); //remove closest trs
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<tr>
<th>PX</th>
<th>Date</th>
<th>Place</th>
<th></th>
<th></th>
</tr>
<tr style="border:1px solid black">
<td><input type="text" name="a[0]"></td>
<td><input type="text" name="sDate[0]"></td>
<td><input type="text" name="Place[0]" value="somthing"></td>
<td><input type="text" name="Pid[0]" value="1"></td>
<td>
Remove
</td>
</tr>
</table>
<button id="addNew">Add</button>
How can I get the highest value in a table column by class? I have tried the following:
HTML
<table>
<tr><td class="speed">1.1</td></tr>
<tr><td class="speed">3.1</td></tr>
<tr><td class="speed">5.5</td></tr>
<tr><td class="speed">2.0</td></tr>
</table>
jQuery/Javascript
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
alert(highestspeed)
}
Also, how can I get all values if > than a certain number?
this.text is undefined for the td element, you need to parse parseFloat($(this).text(), 10);
function gethighestspeeds() {
var speeds = $(".speed").map(function() {
return parseFloat($(this).text(), 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
snippet.log('high: ' + highestspeed);
var num = 2.3;
var array = $(".speed").map(function() {
var flt = parseFloat($(this).text(), 10);
return flt > num ? flt : undefined;
}).get();
snippet.log('array: ' + array)
//if you already have the speeds array
var array2 = speeds.filter(function(val) {
return num < val;
});
snippet.log('array2: ' + array)
}
gethighestspeeds();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="speed">1.1</td>
</tr>
<tr>
<td class="speed">3.1</td>
</tr>
<tr>
<td class="speed">5.5</td>
</tr>
<tr>
<td class="speed">2.0</td>
</tr>
</table>
Try this........
var certainNumber=2.2; //Whatever you want to set
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10) > parseFloat(certainNumber);
}).get();
}
You have to use : $(this).text() instead of this.text in your map function:
return parseFloat($(this).text(), 10);
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;
}
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/>');
}
}
}
});