How to show different json after checking radio button value - javascript

I want to show different json after click into any radio button. 'Option 1' will get option1.json etc.
Is is possible to do it without page refresh?
$('#my_radio_box').change(function(){
selected_value = $("input[name='my_options']:checked").val();
if (selected_value == 'option 2'){
const products =
[
{id: 11,title: '2Macbook Pro', price: 2500.00, qty: 1, image: 'http://lorempixel.com/150/150/'},
{id: 12,title: '2Asus ROG Gaming',price: 1000.00, qty: 1,image: 'http://lorempixel.com/150/150/'},
{id: 13,title: '2Amazon Kindle',price: 150.00,qty: 1,image: 'http://lorempixel.com/150/150/'},
{id: 14,title: '2Another Product',price: 10, qty: 1, image: 'http://lorempixel.com/150/150/'},
];
}
});
$(document).ready(function(){
$('#my_radio_box').change(function(){
selected_value = $("input[name='my_options']:checked").val();
if (selected_value == 'option 2'){
// const products = ...
}
});
});
const products =
[
{id: 1,title: 'Macbook Pro', price: 2500.00, qty: 1, image: 'http://lorempixel.com/150/150/'},
{id: 2,title: 'Asus ROG Gaming',price: 1000.00, qty: 1,image: 'http://lorempixel.com/150/150/'},
{id: 3,title: 'Amazon Kindle',price: 150.00,qty: 1,image: 'http://lorempixel.com/150/150/'},
{id: 4,title: 'Another Product',price: 10, qty: 1, image: 'http://lorempixel.com/150/150/'},
];
function formatNumber(n, c, d, t){
var c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d === undefined ? '.' : d,
t = t === undefined ? ',' : t,
s = n < 0 ? '-' : '',
i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
};
// Allow the formatNumber function to be used as a filter
Vue.filter('formatCurrency', function (value) {
return formatNumber(value, 2, '.', ',');
});
// The shopping cart component
Vue.component('shopping-cart', {
props: ['items'],
computed: {
Total() {
let total = 0;
this.items.forEach(item => {
total += (item.price * item.qty);
});
return total;
}
},
methods: {
// Remove item by its index
removeItem(index) {
this.items.splice(index, 1)
}
}
})
const vm = new Vue({
el: '#app',
data: {
cartItems: [],
items : products
},
methods: {
// Add Items to cart
addToCart(itemToAdd) {
let found = false;
// Add the item or increase qty
let itemInCart = this.cartItems.filter(item => item.id===itemToAdd.id);
let isItemInCart = itemInCart.length > 0;
if (isItemInCart === false) {
this.cartItems.push(Vue.util.extend({}, itemToAdd));
} else {
itemInCart[0].qty += itemToAdd.qty;
}
itemToAdd.qty = 1;
}
}
})
.container{
padding:20px;
max-width:600px;
}
.input-qty {
width: 60px;
float: right
}
.table-cart > tr > td {
vertical-align: middle !important;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<div id="app" class="container">
<div class="text-right"><button class="btn btn-primary" data-toggle="modal" data-target="#cartModal">Cart ({{cartItems.length}})</button></div>
<form id="my_radio_box">
<input type="radio" name="my_options" value="option 1" checked="checked" /> Option 1
<input type="radio" name="my_options" value="option 2" /> Option 2
<input type="radio" name="my_options" value="option 3" /> Option 3
</form>
<!-- Modal -->
<div class="modal fade" id="cartModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Cart</h4>
</div>
<div class="modal-body">
<shopping-cart inline-template :items="cartItems">
<div>
<table class="table table-cart">
<tr v-for="(item, index) in items">
<td>{{item.title}}</td>
<td style="width:120px">QTY:
<input v-model="item.qty" class="form-control input-qty" type="number">
</td>
<td class="text-right">${{item.price | formatCurrency}}</td>
<td>
<button #click="removeItem(index)"><span class="glyphicon glyphicon-trash"></span></button>
</td>
</tr>
<tr v-show="items.length === 0">
<td colspan="4" class="text-center">Cart is empty</td>
</tr>
<tr v-show="items.length > 0">
<td></td>
<td class="text-right">Cart Total</td>
<td class="text-right">${{Total | formatCurrency}}</td>
<td></td>
</tr>
</table>
</div>
<!-- /.container -->
</shopping-cart>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-3 text-center" v-for="item in items">
<img class="img-responsive" :src="item.image" alt="">
<h5>{{ item.title }}</h5>
<h6>${{ item.price | formatCurrency }}</h6>
<p class="text-center"><input v-model="item.qty" type="number" class="form-control" placeholder="Qty" min="1"/></p>
<button #click="addToCart(item)" class="btn btn-sm btn-primary">Add to Cart</button>
</p>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="app.js"></script>

Related

pass data of input "hidden" in modal mvc 5

I'm a new mvc developper, I make a list in my controller, my view show this list and for each row i have a button for a modal view.I want to pass the data of the ViewBag in my list according for each row in my modal.
This is my modal html:
<div class="modal" id="addBadgetoStudentModal-#item.ID" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg animated bounceInDown">
<div class="modal-content">
#using (Html.BeginForm("AddBadgeToStudent", "Badges", new { ID = item.ID }, FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="modal-header">
<h4 class="modal-title">Badges</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="">
<div class="row">
#if (ViewBag.Badges != null)
{
for (var i = 0; i < ViewBag.Badges.Count; i++)
{
<div class="col-lg-3 col-sm-6 col-md-4">
<div class="team-member ">
<div class="row margin-0">
<div class="team-info" style="text-align:center; border: 1.2pt solid #1874BF;">
<img src="#ViewBag.Badges[i].ImageURL" style="width:80%;" class="img-fluid" />
</div>
<div class="team-info" style="text-align:center; width:100%;">
#ViewBag.Badges[i].Label
<br />
<input id="Badge_#ViewBag.Badges[i].ID" class="checkBoxBadgeClass" type="checkbox" />
</div>
</div>
</div>
</div>
}
}
</div>
</div>
</div>
</div>
<div class="modal-footer">
<i class="fa fa-plus-circle"></i> #Resource.Add
</div>
}
</div>
</div>
</div>
<a class="fa fa-pencil-alt" data-toggle="modal" href="#addBadgetoStudentModal-#item.ID" onclick="btnModal()"></a>
This is my List Html View:
#foreach (var item in Model)
{
<tr id="#item.ID">
<td style="text-align:center; width:5%;">
#Html.DisplayFor(modelItem => item.ID)
</td>
<td style="text-align: center; width:25%;">
#item.FullName
</td>
<td style="width:450px;">
#for (var i = 0; i < item.BadgesAssigned.Count; i++)
{
<img src="#item.BadgesAssigned[i].ImageUrl" width="50" title="#item.BadgesAssigned[i].Name" style="float:left;" />
}
<input type="hidden" id="studentBadges_#item.ID" value="#String.Join(",", item.BadgesAssigned.Select(x => x.ID.ToString()))"/>
</td>
}
and this my controller to get my student list and in another table get the badge assigned to a student, so in the list view the student can have 20 badges/25:
public ActionResult BadgeManagement(int? CohortId, int? id)
{
ViewBag.CohortId = db.Cohorts.Select(p => new SelectListItem
{
Text = p.Name,
Value = p.ID.ToString()
});
if (CohortId != null ? CohortId > 0 : false)
{
var cs = db.CohortSubscriptions.Where(student => student.CohortId == CohortId).Include(c => c.Cohorts).Include(c => c.Registrations);
List<BadgesByStudentViewModel> badgesByStudentList = new List<BadgesByStudentViewModel>();
foreach (var student in cs) {
badgesByStudentList.Add(new BadgesByStudentViewModel
{
ID = student.ID,
FullName = student.Registrations.FullName,
BadgesAssigned = db.Enrolled_Students_Badges.Where(x => x.CohortSubscriptionId == student.ID).Select(x => new BadgesAssigned
{
ID = x.ID,
Name = x.Label,
ImageUrl = x.ImageURL
}).ToList()
});
}
ViewBag.Badges = db.Badges.ToList();
return View(badgesByStudentList.ToList());
}
return View(new List<BadgesByStudentViewModel>());
}
I found my solution
This is my html:
<tbody>
#foreach (var item in Model)
{
<tr id="#item.ID">
<td style="text-align:center; width:5%;">
#Html.DisplayFor(modelItem => item.ID)
</td>
<td style="text-align: center; width:25%;">
#item.FullName
</td>
<td style="width:450px;">
#for (var i = 0; i < item.BadgesAssigned.Count; i++)
{
<img src="#item.BadgesAssigned[i].ImageUrl" width="50" title="#item.BadgesAssigned[i].Name" style="float:left;" />
}
</td>
<td style="text-align:center; width:5%;">
<button style="border:none;background: transparent;" data-studentid="#item.ID" data-studentname="#item.FullName" data-badges="#String.Join(",", item.BadgesAssigned.Select(x => x.ID.ToString()))" data-toggle="modal" data-target="#addBadgetoStudentModal" class="modalLink"><i class="fa fa-pencil-alt"></i></button>
</td>
</tr>
}
</tbody>
</table>
<div class="modal" id="addBadgetoStudentModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg animated bounceInDown">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Badges</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="">
<u>#Resource.AddBadgeToStudent:</u>
<br />
<br />
<div class="row">
#if (ViewBag.Badges != null)
{
for (var i = 0; i < ViewBag.Badges.Count; i++)
{
<div class="col-lg-3 col-sm-6 col-md-4">
<div class="team-member ">
<div class="row margin-0">
<div class="team-info" style="text-align:center; border: 1.2pt solid #1874BF;">
<img src="#ViewBag.Badges[i].ImageURL" style="width:80%;" class="img-fluid" />
</div>
<div class="team-info" style="text-align:center; width:100%;">
#ViewBag.Badges[i].Label
<br />
<input id="Badge_#ViewBag.Badges[i].ID" data-badgeid="#ViewBag.Badges[i].ID" data-label="#ViewBag.Badges[i].Label" class="checkBoxBadgeClass" type="checkbox" />
</div>
</div>
</div>
</div>
}
}
</div>
</div>
</div>
</div>
<div class="modal-footer">
<i class="fa fa-plus-circle"></i> #Resource.Edit
</div>
</div>
</div>
</div>
and this is my jquery:
currentStudentId = null;
currentAssignedBadge = [];
$('#BadgeAssignmentTable').dataTable({
responsive: true,
aLengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"]
]
});
$(".modalLink").on("click", function () {
var $pencil = $(this);
var studentId = $pencil.data('studentid');
var badges = $pencil.data('badges');
var studentName = $pencil.data("studentname");
PrepareBadgesModal(studentId, badges.split(","), studentName);
});
PrepareBadgesModal = function (studentId, assignedBadges, studentName) {
currentStudentId = studentId;
console.log(assignedBadges);
currentAssignedBadge = [];
$.each(assignedBadges, function (k, v) { return currentAssignedBadge.push(parseInt(v, 10)); });
$.each(assignedBadges, function (k, v) {
var $badge = $("#Badge_" + v);
$badge.prop("checked", true);
var label = $badge.data("label");
$badge.on("click", function (event) {
var res = ConfirmRemoveBadge($(this), label, studentName);
event.stopPropagation();
});
});
}
ConfirmRemoveBadge = function ($badge, label, studentName) {
var txt = "ATTENTION\r\rÊtes-vous certain de vouloir retirer le badge \"" + label + "\" à " + studentName + "?";
var r = confirm(txt);
if (r == true) {
$badge.prop("checked", false);
$badge.unbind("click");
} else {
$badge.prop("checked", true);
}
}
$("#AssignBadges").click(function () {
ModifyBadgesAction();
});
ModifyBadgesAction = function (badgeList) {
var selBadgeLst = $('input[id^=Badge_]:checked').map(function (k, v) { return parseInt($(v).data('badgeid'), 10); });
//TODO: Close the modal
var removedLst = $.grep(currentAssignedBadge, function (v, k) {
return $.grep(selBadgeLst, function (vv, kk) {
return v == vv;
}).length == 0;
});
var AddedList = $.grep(selBadgeLst, function (v, k) {
return $.grep(currentAssignedBadge, function (vv, kk) {
return v == vv;
}).length == 0;
});
var jsonData = JSON.stringify({ studentId : currentStudentId, AddedList: AddedList, removedLst: removedLst });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Badges/ModifyBadgesAction',
data: jsonData,
success: function (data, textStatus, jqXHR) {
//console.log(data, textStatus, jqXHR);
if (data.code == 0) {
ApplyBadgeActionSuccess(data);
}
else {
ApplyBadgeActionError(data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
ApplyBadgeActionError({ code: jqXHR.status, message: "Technical Error", data: [{ jqXHR: jqXHR, error: errorThrown }] });
}
});
};
ApplyBadgeActionSuccess = function (data) {
alert(data.message);
window.location.reload(true);
}
ApplyBadgeActionError = function (data) {
alert(data.message);
}

How can I clean the filter header of this datatable

I have the following code where I load data in a datatable, and I add some filters by select, but when I create a new datatable this select multiply in the head of the datatable
I have tried with the function destroy, but no resutl still multiply in the head
$("#button_id").click(function(){
var dataSet = [
[ Math.random().toString(36).substring(7), Math.random().toString(36).substring(7), Math.random().toString(36).substring(3), Math.random(), "2011/04/25", "$320,800" ],
[ Math.random().toString(36).substring(7), Math.random().toString(36).substring(7), Math.random().toString(36).substring(3), Math.random(), "2011/07/25", "$170,800" ]];
if ($.fn.dataTable.isDataTable('#dt_detalle'))
{
var tables = $('.dataTable').DataTable();
var table = tables.table('#dt_detalle');
table.destroy();
// alert('xx')
}
var op = $("#Txt_OP").val();
let tabla = $("#dt_detalle").DataTable({
"destroy": true,
initComplete: function() {
this.api().columns(".searchable_option").every( function () {
var column = this;
var select = $('<br><select class="browser-default" style="width:100%"><option value=""></option></select>')
.appendTo($(column.header()))
.on('change', function() {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
},
"order": [
[1, "asc"]
],
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" },
{ title: "Extn." }
],
"select": {
"style": 'os',
"items": 'cell'
}
});
function actualizar() {
/* Calculamos la suma mediante una función de reducción */
let suma = tabla.cells( { selected: true } )
.data()
.reduce(function (a, b) {
let x = parseFloat(a) || 0;
let y = parseFloat(b) || 0;
return x + y;
}, 0
);
/* Asignamos al campo del formulario el resultado obtenido */
$('input[name="autosum"]').val(suma);
}
tabla
.on( 'select', actualizar )
.on( 'deselect', actualizar );
});
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<div class="col-md-3">
<button type="button" id="button_id" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"><i class="fa fa-list"></i> look details
</button>
</div>
<!-- Modal: modalCart -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-fluid" role="document">
<div class="modal-content">
<!--Header-->
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">tittle</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!--Body-->
<div class="modal-body">
<div class="md-form input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text md-addon" id="inputGroupMaterial-sizing-sm">Suma</span>
</div>
<input type="text" class="form-control" value="" name="autosum" readonly>
</div>
<table id="dt_detalle" class="table table-hover table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th class="searchable_option">area</th>
<th>x</th>
<th class="searchable_option">number</th>
<th>x</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<!--Footer-->
<div class="modal-footer">
<button type="button" class="btn btn-outline-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I hope I have explained me well. Greetings

How to modify this demo of vue.js?

demo:
https://jsfiddle.net/8hh0p0ej/
In this demo,there is a selected attribute in items,which control the item selected or not and "allSelected".
Question:
When I use it in my project,the content of items will be gotten form mysql,there is no selected field,the status of one item doesn't need to be recorded,so I don't want to add this field,how to accomplish "Allselected" in this situation?
You can add a selected member to the data after it is fetched.
var vm = new Vue({
el: "#app",
data: {
items: []
},
methods: {
fillIn: function(index, n) {
this.items[index].num = n;
}
},
computed: {
nums: function() {
return [1, 2, 3, 4, 5];
},
allSelected: {
get: function() {
for (var i = 0, length = this.items.length; i < length; i++) {
if (this.items[i].selected === false) {
return false;
}
}
return true;
},
set: function(val) {
for (var i = 0, length = this.items.length; i < length; i++) {
this.items[i].selected = val;
}
}
},
sum: function() {
var totalAmount = 0;
for (var i = 0, length = this.items.length; i < length; i++) {
var item = this.items[i];
if (item.selected === true) {
totalAmount += item.price * item.num;
}
}
return totalAmount;
}
}
});
// Data as it might come from mysql
mysqlData = [{
message: 'Apple',
num: 1,
price: 5
}, {
message: 'Peach',
num: 1,
price: 10
}, {
message: 'Orange',
num: 1,
price: 15
}, {
message: 'Pear',
num: 1,
price: 20
}];
// Modify the data when we put it in the vm
vm.$set('items', mysqlData.map((item) => {
item.selected = false;
return item;
}));
<link href="//cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/css/tether.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//cdn.bootcss.com/bootstrap/4.0.0-alpha.3/css/bootstrap.min.css" rel="stylesheet" />
<script src="//cdn.bootcss.com/bootstrap/4.0.0-alpha.3/js/bootstrap.min.js"></script>
<script src="//cdn.bootcss.com/vue/1.0.26/vue.min.js"></script>
<div class="container">
<div class="card">
<h3 class="card-header">Cart</h3>
<div class="card-block">
<div id="app">
<div class="row">
<div class="col-xs-3">
<label class="c-input c-checkbox">
<input type="checkbox" v-model="allSelected">Select All
<span class="c-indicator"></span>
</label>
</div>
<div class="col-xs-2">
Goods
</div>
<div class="col-xs-5">
Number
</div>
<div class="col-xs-2">
Money
</div>
</div>
<form>
<div class="row" v-for="(index, item) in items">
<div class="col-xs-3">
<label class="c-input c-checkbox">
<input type="checkbox" v-model="item.selected">
<span class="c-indicator"></span>
</label>
</div>
<div class="col-xs-2">
{{ item.message }}
</div>
<div class="col-xs-5">
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-text="item.num">
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li v-for="n in nums">
<a class="dropdown-item" #click="fillIn(index, n)">{{n}}个</a>
</li>
</ul>
</div>
</div>
<div class="col-xs-2">
{{ item.price * item.num }}
</div>
</div>
<div class="row">
<div class="col-xs-3">
Sum
</div>
<div class="col-xs-2">
</div>
<div class="col-xs-5">
</div>
<div class="col-xs-2">
{{ sum }}
</div>
</div>
<button type="submit" class="btn btn-primary" :disabled="sum === 0">Submit</button>
</form>
</div>
</div>
</div>
</div>
You could keep a separate object with the id of the object as a key and a Boolean value, that represents if the item is selected or not.
The items data would only have, message, num and price
While the selected data would have itemid and selected

Angularjs Filter data with dropdown

I am kinda new in angularjs and javascript so please be kind, I have two dropdown items (Ionic Select) both of them holds data from a service. The issue is that I need to filter them in order to work together like: if I choose a company in the first dropdown list, only the reps inside of that company should display in the other dropdown list.
I tried using | filter: byID as I followed in Angularjs documentation but I do not think it is the right way of doing this don't know.
HTML:
<label class="item item-input item-select"">
<div class="input-label">
Company:
</div>
<select>
<option ng-repeat="x in company">{{x.compname}}</option>
<option selected>Select</option>
</select>
</label>
<div class="list">
<label class="item item-input item-select">
<div class="input-label">
Rep:
</div>
<select>
<option ng-repeat="x in represent">{{x.repname}}</option>
<option selected>Select</option>
</select>
</label>
Javascript:
/*=========================Get All Companies=========================*/
$http.get("http://localhost:15021/Service1.svc/GetAllComp")
.success(function(data) {
var obj = data;
var SComp = [];
angular.forEach(obj, function(index, element) {
angular.forEach(index, function(indexN, elementN) {
SComp.push({compid: indexN.CompID, compname: indexN.CompName});
$scope.company = SComp;
});
});
})
/*=========================Get All Companies=========================*/
/*=========================Get All Reps=========================*/
$http.get("http://localhost:15021/Service1.svc/GetAllReps")
.success(function(data) {
var obj = data;
var SReps = [];
angular.forEach(obj, function(index, element) {
angular.forEach(index, function(indexN, elementN) {
SReps.push({repid: indexN.RepID, repname: indexN.RepName, fkc :indexN.fk_CompID});
$scope.represent = SReps;
});
});
})
/*=========================Get All Reps=========================*/
You may solve this problem like my solution process:
my solution like your problem. at first show District list and show Thana list according to selected District. using filter expression
In HTML:
<div>
<form class="form-horizontal">
<div class="form-group">
<div class="col-md-3"><label><i class="fa fa-question-circle fa-fw"></i> District List</label></div>
<div class="col-md-4">
<select class="form-control" ng-model="selectedDist" ng-options="district.name for district in districts">
<option value="">Select</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-3"><label><i class="fa fa-question-circle fa-fw"></i> Thana List</label></div>
<div class="col-md-4">
<select class="form-control" ng-model="selectedThana" ng-options="thana.name for thana in thanas | filter: filterExpression">
<option value="">Select</option>
</select>
</div>
</div>
</form>
</div>
In controller:
$scope.selectedDist={};
$scope.districts = [
{id: 1, name: 'Dhaka'},
{id: 2, name: 'Goplaganj'},
{id: 3, name: 'Faridpur'}
];
$scope.thanas = [
{id: 1, name: 'Mirpur', dId: 1},
{id: 2, name: 'Uttra', dId: 1},
{id: 3, name: 'Shahabag', dId: 1},
{id: 4, name: 'Kotalipara', dId: 2},
{id: 5, name: 'Kashiani', dId: 2},
{id: 6, name: 'Moksedpur', dId: 2},
{id: 7, name: 'Vanga', dId: 3},
{id: 8, name: 'faridpur', dId: 3}
];
$scope.filterExpression = function(thana) {
return (thana.dId === $scope.selectedDist.id );
};
N.B: Here filterExpression is a custom function that return values when selected district id equal dId in thana.
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope,$window, $http) {
$scope.myFunc = function(x) {
$scope.name = x.Name;
$scope.country = x.Country;
$scope.city = x.City;
$scope.x = x;
$("#myModal").modal();
};
$scope.saveData = function(x) {
if(x == ''){
x = angular.copy($scope.names[0]);
x.Name = $scope.name;
x.Country = $scope.country;
x.City = $scope.city;
$scope.names.push(x);
}
else{
x.Name = $scope.name;
x.Country = $scope.country;
x.City = $scope.city;
}
};
$scope.newData = function() {
$scope.name = "";
$scope.country = "";
$scope.city = "";
$scope.x = "";
$("#myModal").modal();
};
$scope.myDelete = function(x) {
if(x.Name=='' && x.Country=='' && x.City==''){
var index = $scope.names.indexOf(x);
$scope.names.splice(index, 1);
}
else{
var deletedata = $window.confirm('are you absolutely sure you want to delete?');
if (deletedata) {
alert('i am');
var index = $scope.names.indexOf(x);
$scope.names.splice(index, 1);
}
}
};
$scope.filterExpression = function(x) {
//alert($scope.country.id);
return (x.countryId === $scope.country.countryId );
};
$scope.names = [{"Name":"Alfreds Futterkiste","City":"","Country":""},{"Name":"Ana Trujillo Emparedados y helados","City":"","Country":""}]
$scope.countryList = [
{countryName : "Pakistan", countryId : 1},
{countryName : "UK", countryId : 2},
{countryName : "Sweden", countryId : 3}
];
$scope.cityList = [
{cityName : "Karachi", cityId : 1, countryId:1},
{cityName : "London", cityId : 2, countryId:11},
{cityName : "Sweden City", cityId : 3, countryId:3}
];
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<style>
.table tr {
cursor: pointer;
}
</style>
<div class="container" ng-app="myApp" ng-controller="customersCtrl">
<pre>{{names}}</pre>
<h2>Hover Rows</h2>
<p>The .table-hover class enables a hover state on table rows:</p>
<table class="table table-hover">
<thead>
<tr>
<th>Sr.No</th>
<th>Name</th>
<th>Country</th>
<th>City</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in names" ng-dblclick="myFunc(x)" >
<td>{{ $index + 1 }}</td>
<td>{{ x.Name }}</td>
<td>{{ x.Country.countryName }}</td>
<td>{{ x.City.cityName }}</td>
<td><span class="glyphicon glyphicon-remove" ng-click="myDelete(x)"></span></td>
</tr>
</tbody>
<tfoot>
<tr ng-click="newData()">
<td colspan="4">
</td>
<td>
<span class="glyphicon glyphicon-plus" ng-click="newData()" cursor="" ></span>
</td>
</tr>
</tfoot>
</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" ng-if="x!=''">Edit Record</h4>
<h4 class="modal-title" ng-if="x==''">Save Record</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" ng-model="name">
</div>
<div class="form-group">
<label for="country">Country:</label>
<!-- <input type="text" class="form-control" id="country" ng-model="country"> -->
<select class="form-control" ng-model="country" ng-options="x.countryName for x in countryList"></select>
</div>
<div class="form-group">
<label for="country">City:</label>
<select class="form-control" ng-model="city" ng-options="x.cityName for x in cityList | filter:filterExpression"></select>
</div>
<input type="hidden" ng-model="x" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="saveData(x)">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="myDelete(x)" ng-if="x!=''">Delete</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

AngularJS : How to make dynamic field button only for last button?

In the dynamic input field is there any option to implement plusSign = true only for the last item ?
(function() {
var app = angular.module('managementApp', []);
// var app = angular.module('managementApp', ['ngRoute']);
app.controller('phonebookController', function($scope, $http) {
$scope.dynamicField = function(buttonStatus, inputIndex) {
if (!buttonStatus) {
$scope.currentContact.contacts.push({
"phone": ""
});
} else {
$scope.currentContact.contacts.splice(inputIndex, 1);
}
};
$scope.currentContact = [{
"phone": "07875 506 426"
}, {
"phone": "+91 9895 319991"
}, {
"phone": "+44 7875 506 426"
}];
$scope.dynamicField = function(buttonStatus, inputIndex) {
if (!buttonStatus) {
$scope.currentContact.push({
"phone": ""
});
} else {
$scope.currentContact.splice(inputIndex, 1);
}
};
$scope.checkIndex = function(totalCount, indexCount) {
indexCount++;
// alert(indexCount);
/*if (totalCount === indexCount) {
//alert("last one");
$scope.plusSign = true;
}else{
$scope.plusSign = false;
}*/
};
});
})();
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="managementApp">
<div class="row" ng-controller="phonebookController">
<div class="form-group" ng-repeat="contact in currentContact" ng-init="checkIndex(currentContact.length, $index);">
<label for="contact-number3" class="col-sm-3 control-label">Contact number {{$index + 1 }}</label>
<div class="col-sm-9">
<div class="input-group">
<input type="tel" class="form-control" placeholder="Contact number {{$index + 1 }}" ng-model="contact.phone">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-init="plusSign = true"
ng-click="plusSign = !plusSign; dynamicField(plusSign, $index);">
<i class="glyphicon " ng-class="plusSign ? 'glyphicon-plus' : 'glyphicon-minus'"></i>
</button>
</span>
</div>
</div>
</div>
</div>
</div>
You can use $last inside ng-repeat which is true if the repeated element is last in the iterator. Or you can do it with css only with .row:last-of-type {/**/}.
check $last in your function for example:-
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="managementApp">
<div class="row" ng-controller="phonebookController">
<div class="form-group" ng-repeat="contact in currentContact" ng-init="checkIndex($last);">
<label for="contact-number3" class="col-sm-3 control-label">Contact number {{$index + 1 }}</label>
<div class="col-sm-9">
<div class="input-group">
<input type="tel" class="form-control" placeholder="Contact number {{$index + 1 }}" ng-model="contact.phone">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-init="plusSign = true"
ng-click="plusSign = !plusSign; dynamicField(plusSign, $index);">
<i class="glyphicon " ng-class="plusSign ? 'glyphicon-plus' : 'glyphicon-minus'"></i>
</button>
</span>
</div>
</div>
</div>
</div>
</div>
controller method
$scope.checkIndex = function(last) {
(last === true)
$scope.plusSign = true;
else
$scope.plusSign = false;
};

Categories