I created a website modul with PHP, MySQL, Bootstrap modal and Jquery. I have 4 checkboxes with datas. I store the datas in database. If the customer selects 2 checkboxes, a bootstrap modal appears with the relations between the 2 selection. It's actually works, but the modal shows the data several times.
In this case, computer1 is connected to computer3, which connected to computer4. So if I select computer1 and computer4, it shows the relations correctly, but several times:
$(document).ready(function() {
$('#checkBtn').click(function getElementRelation(element1, element2) {
var ele = document.getElementsByName("case");
var modal = document.getElementById("modaldata");
var hu = document.getElementsByName("hu");
var hu2 = document.getElementsByName("hu2");
if (modal.innerHTML === "") // if no relation is detected yet put start element
{
modal.innerHTML += element1;
}
//loop in data (this shows datas several times)
for (var i = 0; i < ele.length; i++) {
if (hu[i].innerHTML === element1) //if data = element 1 then put related element
{
modal.innerHTML += hu[i].innerHTML + "--->" + hu2[i].innerHTML + " ";
if (hu2[i].innerHTML !== element2) //if related element != end element call function to get relation between related element and end element
{
getElementRelation(hu2[i].innerHTML, element2);
}
}
}
var start = ""; //hold start element
var end = ""; //hold end element
for (var i = 0; i < ele.length; i++) {
if (ele[i].checked === true) {
if (start === "") {
start = hu[i].innerHTML; //set start element
} else {
end = hu[i].innerHTML; //set end element
}
}
}
checked = $("input[type=checkbox]:checked").length === 2;
if (!checked) {
alert("You must check 2 checkbox!");
return false;
} else {
getElementRelation(start, end);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Checkboxes -->
<div class="container">
<div class="row">
<div class="col-sm-6">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Connect</th>
</tr>
</thead>
<tbody>
<tr>
<!-- Checkboxes -->
<td><input type="checkbox" name="case"></td>
<td><p name="hu" value="Computer1">Computer1</p></td>
<td><p name="hu2" value="Computer3">Computer3</p></td>
</tr>
<tr>
<td><input type="checkbox" name="case"></td>
<td><p name="hu" value="Computer2">Computer2</p></td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="case"></td>
<td><p name="hu" value="Computer3">Computer3</p></td>
<td><p name="hu2" value="Computer4">Computer4</p></td>
</tr>
<tr>
<td><input type="checkbox" name="case"></td>
<td><p name="hu" value="Computer4">Computer4</p></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- Input button -->
<div class="container">
<div class="row">
<div class="col-sm-12">
<input type="button" id="checkBtn" value="View" data-toggle="modal" data-target="#myModal" class="btn btn-info">
</div>
</div>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Title</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="modaldata">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Select Computer1 and Computer3 and shows data several times
First, the paragraph tag does not have any attributes name or value. If you want to create new attributes, use HTML5 data-attributes.
To make the subsequent JS code easier, we will add these attributes to the input element. For example,
<tr>
<td><input type="checkbox" name="case" data-name="Computer1" data-connect="Computer3"></td>
<td>Computer1</td>
<td>Computer3</td>
</tr>
Second, your JS code was kind of confusing. My guess as to why you are getting duplicate results is because you are recursively calling getElementRelation().
I would simplify your code as below
$(function() {
// cache jQuery objects that we will be re-using
var checkBoxes = $("input[name=case]");
var myModal = $("#myModal");
// get all relationships i.e. key = name, value = connect or null
var relations = {};
checkBoxes.each(function () {
relations[this.dataset.name] = this.dataset.connect;
});
// when the getElementRelation() function is called normally, it is expected
// to have 2 arguments (element1 and element2);
// but as an event handler it will have 1 argument (Event object)
$('#checkBtn').click(function getElementRelation(e) {
// get checked checkboxes
var checkedBoxes = checkBoxes.filter(":checked");
// validate first
if (checkedBoxes.length != 2) {
alert("You must check 2 checkbox!");
return false;
}
// build modal body
var html = '';
var current = checkedBoxes[0].dataset.name,
end = checkedBoxes[1].dataset.name;
while (current) {
html += current;
// check if it is connected
var next = relations[current];
// if it is not connected, stop
if (!next) {
html = 'Not related';
break;
}
// otherwise append HTML
html += ' -> ' + next + '<br>';
// if it is the end, stop
if (next == end) break;
// you may want to delete the key to avoid any infinite loop in case
// delete relations[current];
// start over using connected one
current = next;
}
// update modal
myModal.find('.modal-body').html(html);
// open the modal dynamically once it is ready
myModal.modal('show');
});
});
One last thing, back in your HTML, remove data-toggle="modal" and data-target="#myModal" as we are opening the modal dynamically.
Demo
$(function() {
// cache jQuery objects that we will be re-using
var checkBoxes = $("input[name=case]");
var myModal = $("#myModal");
// get all relationships i.e. key = name, value = connect or null
var relations = {};
checkBoxes.each(function() {
relations[this.dataset.name] = this.dataset.connect;
});
$('#checkBtn').click(function() {
// get checked checkboxes
var checkedBoxes = checkBoxes.filter(":checked");
// validate first
if (checkedBoxes.length != 2) {
alert("You must check 2 checkbox!");
return false;
}
// build modal body
var html = '';
var current = checkedBoxes[0].dataset.name, // start with
end = checkedBoxes[1].dataset.name; // end with
while (current) {
html += current;
// check if it is connected
var next = relations[current];
// if it is not connected, stop
if (!next) {
html = 'Not related';
break;
}
// otherwise append HTML
html += ' -> ' + next + '<br>';
// if it is the end, stop
if (next == end) break;
// start over using connected one
current = next;
}
// update modal
myModal.find('.modal-body').html(html);
// open the modal dynamically once it is ready
myModal.modal('show');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Checkboxes -->
<div class="container">
<div class="row">
<div class="col-sm-6">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Connect</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="case" data-name="Computer1" data-connect="Computer3"></td>
<td>Computer1</td>
<td>Computer3</td>
</tr>
<tr>
<td><input type="checkbox" name="case" data-name="Computer2"></td>
<td>Computer2</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="case" data-name="Computer3" data-connect="Computer4"></td>
<td>Computer3</td>
<td>Computer4</td>
</tr>
<tr>
<td><input type="checkbox" name="case" data-name="Computer4"></td>
<td>Computer4</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- Input button -->
<div class="container">
<div class="row">
<div class="col-sm-12">
<input type="button" id="checkBtn" value="View" class="btn btn-info">
</div>
</div>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Title</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="modaldata">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Related
I have a table that I want to be hidden there is no data to be displayed.
I have a controller action that returns data to display for the table. If data is returned, I want the table to be show, otherwise I want it hidden. I have tried several approaches to this and it seems like my fix is working (for a few seconds) but then once the controller returns the model, the table becomes hidden again. I am doing something wrong. How can I fix this? Below is my code:
HTML:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "submitForm"}))
{
<div class="row">
<div>
#Html.DropDownList("CasinoID", Model.TerminalReceiptPostData.CasinoIdDDL, "Select Casino", new { id = "cIdSearch", #class = "custom-class-for-dropdown card" })
</div>
<div>
<input id="datepicker" class="datepicker-base card" name="Date" placeholder="MM/DD/YYY" type="text"/>
</div>
<div>
<button type="submit" class="btn btn-sm btn-primary" id="search"> Search Transactions</button>
</div>
</div>
}
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
Controller action:
[HttpPost]
public ActionResult Index(string CasinoID, DateTime Date)
{
//var id = Int32.Parse(Request.Form["CasinoID"].ToString());
var Cid = Request.Form["CasinoID"];
Cid = GetNumbers(Cid);
var id = Int32.Parse(Cid);
var model = TRBL.GetTransactionTestsData(id, Date);
model.TerminalReceiptPostData = TRBL.GetCasinosDDL();
return View(model);
}
and finally my JS function:
window.onload = function () {
$("#ReceiptsMainDiv").toggle();
var rowCount = $("#rowindex").length;
console.log(rowCount);
if (rowCount > 0) {
$("#ReceiptsMainDiv").toggle();
}
};
As you can see, the Form at the top contains the button, and the block below is the table that needs to be toggled.
Let me know if there is anything else you guys would need.
When you have results to show, <tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))"> will not produce ids of "rowIndex" (unlike what you might be expecting). Instead, you will have "rowIndex0", "rowIndex1", etc. Therefore, after rowCount will be zero, and your will not toggle.
My code is to create search suggestions after triggering the 'keyup' event, hence creating dynamic elements with a class "suggestion-box". On clicking any of "suggestion-box" classes, new dynamic elements, each with parent class "transaction-entry", are created. Each of the dynamically created "transaction-entry" classes has child class 'quantityInput' which is an input element. The major problem is this, each of the 'quantityInput' classes display their corresponding input values when delegated to a static element through the 'keyup' event trigger but not their corresponding indexes (displays only 0).
HTML CODE
<div class="col-sm-1">
<button type="button" id="delete-transact" class="btn btn-default" data-toggle="tooltip" title="Delete All Entries" data-placement="right">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</div>
<!-- Input field for search suggestion -->
<form method="POST" action="{{URL::to('/search/transaction')}}" id="transAction">
{{ csrf_field() }}
<div class="col-sm-12">
<div class="form-group">
<input type="text" name="searchItem" id="transProductSearch" class="form-control" value="" title=""
placeholder="Search product">
<!--Container for dynamically created class "suggestion-box"-->
<div id="suggestion-container"></div>
</div>
</div>
</form>
<div class="cover">
<div class="table-responsive">
<form action="" method="">
<table class="table table-hover">
<thead>
<tr>
<th>Product</th>
<th>Quantity purchased</th>
<th>Quantity Available</th>
<th>Price</th>
</tr>
</thead>
<!--Container for dynamically created class "transaction entry"-->
<tbody id="transaction-body">
</tbody>
<tfoot>
<tr class="tfoot">
<td>Total</td>
<td class="transactionTotal"></td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
</form>
</div>
</div>
JQUERY CODE
$('#transProductSearch').on('keyup',function (e) { //Event listener for ajax request
e.preventDefault();
if($(this).val() !== ""){
$.ajax({
type: "POST",
url: $('#transAction').attr('action'),
data: $('#transAction').serialize(),
success: function (response) {
$(".suggestion-box").remove();//Removing every dynamically created "suggestion-box" class on every successful AJAX request;
pEntities = [];
response = jQuery.parseJSON(response);
$.each(response, function (indexInArray, value) {
$("#suggestion-container").append($('<div>',{class:"suggestion-box", text:value.productName}));
pEntities[indexInArray] = {prodQuantity:"",prodId:"",prodPrice:"",prodName:""};
pEntities[indexInArray].prodQuantity = value.quantity;
pEntities[indexInArray].prodId = value.id;
pEntities[indexInArray].prodPrice = value.price;
pEntities[indexInArray].prodName = value.productName;
});
},
error: function () {
console.log($('#transAction').val());
}
});
}
else{
$('.suggestion-box').remove()//Removing every suggestion box if input field is empty
}
});
$('#suggestion-container').on("click",'.suggestion-box', function (e) { // Event delegation to append new "transaction-entry" class
var index = $(this).index();
$('#transaction-body').append('<tr class="transaction-entry"><input hidden class="prodId" value="'+pEntities[index].id+'"/><td>'+pEntities[index].prodName+'</td><td><input class="quantityInput" style="color:black" type="number"></td><td>'+pEntities[index].prodQuantity +'</td><td class="productPrice">'+pEntities[index].prodPrice +'</td></tr>');
$('.suggestion-box').remove();
})
$('#delete-transact').click(function (e) {//Event listener to remove all transaction entry classes
e.preventDefault();
$('#transaction-body').empty();
})
$('#transaction-body').on("keyup",'.quantityInput',function (e) {//Event Delegation to output quantityInput value and index
console.log($(this).val()+" "+$(this).index());
});
I am currently using appendTo to add dynamic rows. What I want to happen is that if I will click one of the td (not including the remove button), It will open a bootstrap modal window and get the value of other td of its belonging row. here's the image.
Here's my code adding dynamically that I want to get the value of td and pass it to bootstrap modal.
function AddOrder(new_code, new_name, new_qtty, new_cost) {
var rows = "";
var code = new_code;
var name = new_name;
var cost = new_cost;
var qtty = new_qtty;
rows +=
'<tr>"' +
'<td class="item_code" data-toggle="modal" data-target="#mymodal">'+code+'</td>'+
'<td class="item_name" data-toggle="modal" data-target="#mymodal">'+name+'</td>'+
'<td class="item_qtty" data-toggle="modal" data-target="#mymodal">'+qtty+'</td>'+
'<td class="item_cost" data-toggle="modal" data-target="#mymodal">'+cost+'</td>'+
'<td>'+'<button class="btn remove-button">X</button>'+'</td>'+
'</tr>';
$(rows).appendTo("#dynamic_added tbody");
}
I tried putting putting onclick on td with data-toggle="modal" data-target="#mymodal" but only the modal is working not the function I'm using for example:
function GetData() {
$('.item_code').click(function(){
alert($(this).closest('tr').find('.item_code'));
});
}
I just solved my own problem just a bootstrap modal call is all I am missing.
I addded a class getdata that I will call to my javascript function
function AddOrder(new_code, new_name, new_qtty, new_cost) {
var rows = "";
var code = new_code;
var name = new_name;
var cost = new_cost;
var qtty = new_qtty;
rows +=
'<tr>"' +
'<td class="item_code getdata" onclick="GetData();">'+code+'</td>'+
'<td class="item_name getdata" onclick="GetData();">'+name+'</td>'+
'<td class="item_qtty getdata" onclick="GetData();">'+qtty+'</td>'+
'<td class="item_cost getdata" onclick="GetData();">'+cost+'</td>'+
'<td>'+'<button class="btn remove-button">X</button>'+'</td>'+
'</tr>';
$(rows).appendTo("#dynamic_added tbody");
}
If I will click anywhere to the td except the button It will pop up the modal and pass the current data of that row.
function GetData() {
$(document).on('click', '.getdata', function(){
$('#mymodal').modal();
var modal_code =$(this).closest('tr').find('.item_code').text();
var modal_name =$(this).closest('tr').find('.item_name').text();
var modal_qtty =$(this).closest('tr').find('.item_qtty').text();
var modal_cost =$(this).closest('tr').find('.item_cost').text();
var modal = $("#mymodal"); // this is the id of my modal
modal.find('.modal-body').text(modal_code + modal_name + modal_qtty + modal_cost);
});
}
Do you want something like this:
$('.item_code, .item_name, .item_qtty, .item_cost').click(function() {
$('.modal-body').html($(this).closest('tr').html());
$('#myModal').modal('show');
});
td {
border: 1px solid black;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table id="dynamic_added">
<tbody>
<tr>
<td class="item_code">code_1</td>
<td class="item_name">name_1</td>
<td class="item_qtty">qtt_1</td>
<td class="item_cost">cost_1</td>
<td>
<button class="btn remove-button">X</button>+</td>
</tr>
<tr>
<td class="item_code">code_2</td>
<td class="item_name">name_2</td>
<td class="item_qtty">qtt_2</td>
<td class="item_cost">cost_2</td>
<td>
<button class="btn remove-button">X</button>+</td>
</tr>
<tr>
<td class="item_code">code_3</td>
<td class="item_name">name_3</td>
<td class="item_qtty">qtt_3</td>
<td class="item_cost">cost_3</td>
<td>
<button class="btn remove-button">X</button>+</td>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I am trying to make items not in list but in div and if an item is clicked, the div will be in different colors and the item will be added into a column but if the item is clicked again, the item will changed to original color and in the column the item will be gone. I just can't think how to do it in angular way. I came to another option to be able to add in the column and to remove the item, there's a remove button but I am still curious how the select and deselect can be done.
This is what I have in my html (ignore my btn btn-primary classes I was using button to give it a try in the first place)
<!--Select App Features-->
<div class="panel-heading" ng-controller="FeaturesController as featuresCtrl">
<h1 class="text-center">App Features</h1>
<div class="text-center">
<div ng-repeat="app in featuresCtrl.apps" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.addPrices(app.name, app.price)">{{ app.name }}</div><br>
</div>
<div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Device Added</th>
<th>Device Price</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="appList in featuresCtrl.listAppPrices">
<td>{{ appList.name }}</td>
<td>{{ appList.price }}</td>
<td><button class="btn btn-default" ng-click="featuresCtrl.remove($index)">Remove</button></td>
</tr>
</table>
<div>Total : {{ featuresCtrl.totalAppPrice() }}</div>
</div>
</div><!-- end select app features / FeaturesController-->
My controller in js
//Controller for app features
app.controller("FeaturesController", function(){
this.apps = features;
this.listAppPrices = [];
// add name and price into the new array which is used to show in the table
this.addPrices = function(name, price){
//Checks if the exact name, price property exists in the array and return boolean
var found = this.listAppPrices.some(function (e){
console.log(e.name);
return ((e.name === name) && (e.price === price)) ;
});
//If found not true then push the new values into the array
if(!found){
this.listAppPrices.push({name: name, price: price});
}
};
// adds all the prices of the array which gives the total
this.totalAppPrice = function(){
var total = 0;
for(var i = 0; i < this.listAppPrices.length; i++){
total += this.listAppPrices[i].price;
}
return total;
};
// remove the whole object in the array when remove is clicked
this.remove = function(index) {
this.listAppPrices.splice(index, 1);
};
});
I kind of having the idea of how this can be done but I just can't think of the code to write it.
P.S. the codes are simple, I just learned it in code school and wanted to created something for fun to educate myself. Thanks in advance people
angular.module("stack", [])
.controller("FeaturesController", function($scope) {
// this.apps = features;
this.listAppPrices = [];
this.apps = [{ "name": "a1", "price": "12" }, { "name": "a2", "price": "13" }, { "name": "a3", "price": "14" }];
$scope.dummyArray = [];
var f = 0,
x = 0,
rem = false;
this.setSelected = function(app, index) {
console.log("app ", app);
//remove an item
if (app.selected) {
console.log(" list ", $scope.dummyArray);
$scope.dummyArray.forEach(function(e, ind) {
if (e.name === app.name) {
console.log(ind, " e ", e);
rem = true;
$scope.dummyArray.splice(ind, 1);
}
});
console.log("dumm ", $scope.dummyArray);
this.listAppPrices = $scope.dummyArray;
} else {
rem = false;
}
//used to select a div and change its colour
app.selected ? app.selected = false : app.selected = true;
//add an item
if (!rem) {
if ($scope.dummyArray.length) {
$scope.dummyArray.forEach(function(each) {
console.log("each ");
if (each.name !== app.name) {
console.log("inside if ");
f = 1;
}
});
} else {
console.log("inside else ");
$scope.dummyArray.push(app);
}
if (f === 1) {
f = 0;
console.log("push");
$scope.dummyArray.push(app);
}
console.log(" list--> ", $scope.dummyArray.length);
this.listAppPrices = $scope.dummyArray;
}
}
});
.selected {
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="stack">
<head>
<title>stack</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="panel-heading" ng-controller="FeaturesController as featuresCtrl">
<h1 class="text-center x">App Features</h1>
<div class="text-center">
<div ng-repeat="app in featuresCtrl.apps track by $index" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.setSelected(app,$index)" ng-class="{selected: app.selected}">{{ app.name }}</div>
<!-- <div ng-if="(c%2===0)" ng-repeat="app in featuresCtrl.apps" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.setSelected(app)">{{ app.name }}</div> -->
<br>
</div>
<div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Device Added</th>
<th>Device Price</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="appList in featuresCtrl.listAppPrices">
<td>{{ appList.name }}</td>
<td>{{ appList.price }}</td>
<td>
<button class="btn btn-default" ng-click="featuresCtrl.remove($index)">Remove</button>
</td>
</tr>
</table>
<div>Total : {{ featuresCtrl.totalAppPrice() }}</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script type="text/javascript" src="controller.js"></script>
</body>
</html>
I haven't added the functionality of remove button.I also haven't count the totalAppPrice. Otherwise your problem is solved :) .
I am using Javascript to edit the property of a row in a List of items and i am following a HTML view like this
ON edit button click i am showing a popup and on Save event of popup i want to set the properties of a selected row .
From html console i can see naming pattern is like name=[1].IsVerified [2].isVerified etc or in general [counter].Property But when i try to access element using JQUery i am not getting the element
#model IList<RoyaltyDb.Models.VerifyLicensorModel>
<table class="table">
<tr>
<th>
Licensor
</th>
<th>
Address
</th>
<th>
Status
</th>
<th>
Verify
</th>
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#Html.HiddenFor(m => m[i].Licensor)
#Html.DisplayFor(m => m[i].Licensor)
</td>
<td>
#Html.TextAreaFor(m => m[i].Address)
</td>
<td>
#Html.LabelFor(m => m[i].IsVerified)
#Html.CheckBoxFor(m => m[i].IsVerified, new { #disabled = "disabled" })
<br />
#Html.HiddenFor(m => m[i].ActionId)
#Html.HiddenFor(m => m[i].ReferenceId)
</td>
<td>
<a onclick="SetProperties('#Model[i].Licensor')" class="btn">Verify</a>
</td>
</tr>
}
</table>
<!-- Modal HTML -->
<div id="VerifyLicensorModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Verify Licensor</h4>
<input type="hidden" id="targetPopup" />
</div>
<div class="modal-body" id="VerifyLicensorDetails">
</div>
<div class="modal-footer">
<a class="btn btn-primary" onclick="confirmLicensor()">Confirm</a>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
function SetProperties(name)
{
//Showing a POPUp Here on element VerifyLicensorModal
}
function confirmLicensor()
{
//Set the corresponding IsVerified checkbox to true
//Set values of ActionId and ReferenceId params in the hidden fields
//ActionId ReferenceId
}
So how can i set the value of a property field from javascript
Rather than polluting your markup with behavior, use Unobtrusive Javascript. Give you link a class name and add the value of the Licensor property as a data- attribute and move the 2 hidden inputs into the same table cell for easier selection
<td>
#Html.HiddenFor(m => m[i].ActionId)
#Html.HiddenFor(m => m[i].ReferenceId)
Verify
</td>
var currentCell;
$('.verify').click(function() {
currentCell = $(this).closest('td');
licensor = $(this).data('licensor');
// get your partial view and display the popup
});
Similarly give the confirm button a unique id attribute
$('#confirm').click(function() {
var inputs = currentCell.children('input');
inputs.eq(0).val(....); // set the value of ActionId
inputs.eq(1).val(....); // set the value of ReferenceId
});
Note that you question indicates Set the corresponding IsVerified checkbox to true. Because this is in the previous cell, you could do it using
currentCell.prev('td').find('input[type="checkbox"]').prop(checked, true);
however you have disabled the checkbox using new { #disabled = "disabled" } which means it wont post back, but the associated hidden input generated by CheckBoxFor() will, meaning that irrespective of checking it, you will always post back false
If the checkbox is intended to give a visual representation that verification has been completed, then a better approach would be to include a hidden input bound to IsVerified and an unbound checkbox.
<td>
<input type="checkbox" disabled="disabled" />
</td>
<td>
#Html.HiddenFor(m => m[i].ActionId)
#Html.HiddenFor(m => m[i].ReferenceId)
#Html.HiddenFor(m => m[i].IsVerified)
Verify
</td>
Then you can 'check' the checkbox as noted above and include
inputs.eq(2).val("True"); // set the value of IsVerified
in the script
You may also want to consider deleting the 'Verify' link from the DOM once you close the popup (assuming you don't want to verify it again
currentCell.children('a').remove();
<tbody>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
<input typye="hidden" class="index" value="#i"/>
#Html.HiddenFor(m => m[i].Licensor)
#Html.DisplayFor(m => m[i].Licensor ,{#id="liecenor-#i"})
</td>
</tr>
}
</tbody>
</table>
<script>
$(".table > tbody> tr").each(function () {
var index=$(this).find('.index').val();
var $id="#licensor-"+index;
alert($($id).val());
}
</script>