How to query dom element ID with JQuery Template? - javascript

I would like to manipulate values on a JQuery template, perhaps with an inline expression or function. I am having trouble selecting the elements in order which to grab their values to perform these tasks. Here's the code:
<td class="currency">
<span id="discounted_amount">${Globalize.format(DiscountAmount, "c2")}</span>
</td>
<td class="currency">
<span id="totalAmt">${Globalize.format(InvoiceAmount, "c2")}</span>
</td>
I'm trying to basically evaluate the discounted_amount, and if there's a value, to subtract that from the totalAmt. I would like to do this on the client, without any further ajax calls. I've seen some examples of this where people have used {{if}} {{else}} {{/if}} or {{html somefunction();}}. I've just not had any success myself. Here's the function I'd like to call, or a similar structure based on whatever works best for the jquery template implementation.
function calculateDiscountedTotal() {
var discountedAmount = $('#discounted_amount').val();
var totalAmt = $('#total_amount').val();
var discountedTotal = function () {
return totalAmt - discountedAmount;
}
return discountedTotal();
}

I am unsure what template system you're using but it looks like you want the element text not the value. Value is reserved for input elements.
var discountedAmount = parseInt($('#discountered_amount').text());

function calculateDiscountedTotal() {
var discountedAmount = parseInt( $('#discounted_amount').text());
var totalAmt = parseInt($('#totalAmt').text());
var discountedTotal = function () {
return totalAmt - discountedAmount;
}
return discountedTotal();
}
console.log(calculateDiscountedTotal());
});`enter code here`

Related

How to get all data-id and amount from html page using jQuery and post it via ajax with data

How can i get all data-id and amount from this HTML page using jquery. After getting those value... I want to push it to array then post via ajax. This is a laravel project. I am not using Form here.
This is that image, from where I want to get value
//Here is the Html code
<?php $i=1 ?>
#foreach($expanse as $expanse)
<tr>
<td class="text-center">{{$i}}</td>
<td>
<h4 class="expVal" data-id="{{$expanse->id}}">{{$expanse->name}}</h4>
</td>
<td class="text-right">
{{$expanse->rent}}
</td>
</tr>
<?php $i++ ?>
#endforeach
You can get all the data Ids and amount like this
var ids = [],amounts = [];
$(".expVal").each(function(){
ids.push($(this).data('id'));
var b = $(this).parent().next().find('a.expanseRent').text();
amounts.push(b);
})
Another method would be
var datas=[];
$(".expVal").each(function(){
var a = $(this).data('id');
var b = $(this).parent().next().find('a.expanseRent').text();
datas.push(a+":"+b);
})
You can loop through the each .expVal elements in jquery and then you can get the data-id attribute using jquery.
After that, you can push this values into some array.
var data_id_array=[];
$( ".expVal" ).each(function( index ) {
data_id_array.push($(this).attr('data-id'));
});
For rent, add rent in data-rent attribute like this.
{{$expanse->rent}}
then, do same process like this to get rent.
var rent_array=[];
$( ".expanseRent" ).each(function( index ) {
rent_array.push($(this).attr('data-rent'));
});
So, for your output,as you mentioned in comment,loop through the data_id_array array and create json item like you want and push it into the finalArray like this.
var finalArray = [];
var i;
for (i = 0; i < data_id_array.length; ++i) {
var itemArr={};
itemArr[data_id_array[i]] = rent_array[i];
finalArray.push(itemArr);
}
So at the end, finalArray will contain all the items like [{1:1200},{2:3000}] like this.
You can get data-* using jquery's data() like this
$(".expVal").data("id")
*assuming you have .expVal class in each <td>.
var attrs = [];
var vals = [];
$(".expVal").each(function(){
attrs.push($(this).attributes.nodeName);
vals.push($(this).data("id")+":"+$(this).data("rent"));
})
Then pass it into your ajax POST call like this
$.ajax({
type: 'POST',
url: "url",
data: dataIDs
});
You can do a query like, which will return you an object indexed in the order of occurrence of the element in the DOM.
$("[data-id]")
Additionally i would also include the amount as a data attribute in the same element, something like
<h4 class="expVal" data-id="{{$expanse->id}}" data-amount="{{$expanse->rent}}">{{$expanse->name}}</h4>
and now through dataset property you will be able to access,
$("[data-id]")[0].dataset.amount
here is the documentation on the data attribute
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

get autogenerated id of list item on click not working [duplicate]

Given this HTML code:
<td role-id="#Model.Id">
#Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole()'></div>
</td>
I need to retrieve role-id when clicking on the div.
JS code:
function UpdateRole() {
$("#ModalUser").show();
var role_id = $(this).parent().attr("role-id");
var user_id = $(this).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};
Both values are undefined, how can I get role-id without this?
Better approach is to use jQuery event binding, but using your approach, pass this context from called function:
Problem: In your example, this is not the element on which event is invoked but window!
function UpdateRole(that) {
$("#ModalUser").show();
var role_id = $(that).parent().attr("role-id");
var user_id = $(that).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};
<td role-id="#Model.Id">
#Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole(this)'></div>
</td>
Using jQuery event-binding:
function UpdateRole() {
$("#ModalUser").show();
var role_id = $(this).parent().attr("role-id");
var user_id = $(this).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
}
$('.update_user').on('click', UpdateRole);
<td role-id="#Model.Id">
#Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole(this)'></div>
</td>
You should register your event using jQuery, this makes it much easier to find the calling element:
$('.update_user').click(UpdateRole);
You can now:
function UpdateRole() {
var clickedElement = $(this);
$("#ModalUser").show();
var role_id = clickedElement.parent().attr("role-id");
var user_id = clickedElement.parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};
this is very simple you need to update this line with . data-* is html5 new attribute for setting and getting data
$(".update_user").on("click",function(){
elm=$(this).parent().data("role-id");
elm // this element consist of role id, now you can use this variable
});

AngularJS namespace for function call in view template

I have a div with controller like this
<div ng-controller= "merchandiseListCtrl as ml">
In the js file, I have a couple of function calls and render an object on return.
vm.getlaptopTotal = (productCatergory) => getTotal(productCatergory);
var getTotal = function (_) {
var res = {
count: 0,
total: 0,
products: []
};
_.map((item) =>{
if(item.purchased){
res.count += 1;
res.total += item.price;
res.products.push(item.product);
}
});
return res;
};
So, it is obvious that I'm returning obj res with properties: count, total, and products.
In the HTML view template, I want to have to shorter namespace, shortcut to reduce the pattern ml.fn(x).products of my function call to return the properties' values for some fields. In other words, I want to assign something like ng-bind ='myTotal = ml.fn(x)', but then I run into ton of errors about $rootScope. What should I do to have a better namespace for this scenario, and complexity may go this far: funcObj.subobj.property.childproperty.grandchildproperty ? So accessibility and readibility can be accomplished?
Here is my HTML code
<div>{{ml.myTotal = ml.getlaptopTotal(ml.laptops)}}>
<!-- display the selection -->
Laptop count: {{ ml.myTotal.count }} units
<br>
<div ng-if="ml.myTotal.products">
<ul ng-repeat="product in ml.myTotal.products">
<li>{{$index+1}}) {{product}}</li>
</ul>
</div>
<br>
</div>
EDIT 1: Ran into this error because now the products array, funcObj().products is dynamic. Don't know how to fix yet. But previously, I use funcObj() as an ng-click event handler.
Thanks,

Move Through Object List

<div id="team-name">{{teams[0].name}}</div>
<button id="next">Next</button>
When the "next" button is hit I would like the team-name to be the next team name in the list, i.e. 0 becomes 1?
I have a feeling I need JS to do this - but I am not sure how I would use JS to do this.
Also, the list is generated from the server.
UPDATE
{{ }} is part of a templating system - Jinja2 to be precise.
The teams list is passed into the webpage through Jinja2 - so the webpage has access to the entire teams list - I hope that makes sense.
class Team(db.Model):
__tablename__ = 'Team'
name = db.Column(db.String(21))
matches_total = db.Column(db.Integer())
matches_won = db.Column(db.Integer())
matches_lost = db.Column(db.Integer())
Make a list containing the names available as team_names and update your template like this:
<div id="team-name" data-index="0" data-entries="{{ team_names|tojson }}">{{teams[0].name}}</div>
<button id="next">Next</button>
In case you are using flask which seems to be the case, pass this to your render_template() call:
team_names=[t.name for t in Team.query]
Then you can use the following jQuery snippet to do what you want:
$('#next').on('click', function(e) {
e.preventDefault();
var nameElem = $('#team-name');
var entries = nameElem.data('entries');
var index = (nameElem.data('index') + 1) % entries.length;
nameElem.text(entries[index]).data('index', index);
})
Note: This answer assumes the list is not too big.

Passing values to ko.computed in Knockout JS

I've been working for a bit with MVC4 SPA, with knockoutJs,
My problem is I want to pass a value to a ko.computed. Here is my code.
<div data-bind="foreach: firms">
<fieldset>
<legend><span data-bind="text: Name"></span></legend>
<div data-bind="foreach: $parent.getClients">
<p>
<span data-bind="text: Name"></span>
</p>
</div>
</fieldset>
</div>
self.getClients = ko.computed(function (Id) {
var filter = Id;
return ko.utils.arrayFilter(self.Clients(), function (item) {
var fId = item.FirmId();
return (fId === filter);
});
});
I simply want to display the Firmname as a header, then show the clients below it.
The function is being called, but Id is undefined (I've tried with 'Firm' as well), if I change:
var filter = id; TO var filter = 1;
It works fine,
So... How do you pass a value to a ko.computed? It doesn't need to be the Id, it can also be the Firm object etc.
Each firm really should be containing a list of clients, but you could use a regular function I think and pass it the firm:
self.getClientsForFirm = function (firm) {
return ko.utils.arrayFilter(self.Clients(), function (item) {
var fId = item.FirmId();
return (fId === firm.Id());
});
});
Then in html, $data is the current model, in your case the firm:
<div data-bind="foreach: $root.getClientsForFirm($data)">
Knockout doesn't allow you pass anything to a computed function. That is not what it is for. You could instead just use a regular function there if you'd like.
Another option is to have the data already in the dataset on which you did the first foreach. This way, you don't use $parent.getClients, but more like $data.clients.

Categories