I have a page where users input quantities for items and various totals are calculated using information pertaining to said items. I'm attempting to display aggregates of the items' totals and in order to properly obtain the values I need, I'm checking to make sure each element involved in the calculation has some kind of value before attempting to do anything. However, when I attempt to check, an error is thrown saying that the method is undefined.
if(itemTotals[i].innerHTML != "" && itemMaps[i].innerHTML != "" && itemCogs[i].innerHTML != "" && itemQuantities[i].value != ""){
//Increment totals
}
The itemQuantities[i].value part is what throws the error. I've tried using .val() and .attr("value") but none of them work. I merely get the message that whatever I tried isn't a function. How can I retrieve each input field's value in this context? Am I retrieving the input fields improperly?
The array is initialized as follows.
var itemQuantities = document.getElementsByClassName("inputQty");
The other arrays involved in calculations use the same .getElementsByClassName method and according to the console, all of the table cells pertaining to the class names I specified (they're not important to this scenario) are retrieved without error.
I just noted that you are indexing the variables with a "i" indexer, so if these lists doesn't have the same length, you are in trouble.
Just make sure that these lists are symmetrical and have the same length.
.val() and .attr() are jQuery methods. They don't exist in normal Javascript.
You get the elements with this:
var itemQuantities = document.getElementsByClassName("inputQty");
getElementsByClassName is a 'normal' javascript method. So you don't get jQuery additions to the elements by default.
try this way:
var itemQuantities = $('.inputQty');
then use the .val() and .attr() methods on them.
and instead of using index to iterate through the list you can do it like this:
itemQuantities.each(function(item) {
...
doWhateverYouWantWithEach($(item));
...
});
or
itemQuantities.each(function() {
...
doWhateverYouWantWithEachItem($(this));
...
});
The .value attribute works. I just wasn't properly checking to see if the input was empty. The input in the quantity boxes is used to multiply various costs in order to determine certain aggregates. I wound up using isNaN() to achieve the desired result.
Related
At the moment I am storing a few objects in Firebase. After successfully retrieving the items from Firebase and storing them in a firebaseArray, I want to further thin out the unwanted elements by deleting the elements in the firebaseArray that do not have the desired property. Consider my code at the moment, that does not do as wanted, however there are no errors in the console:
var querylatestPosts = firebase.database().ref("Topics");
$scope.latestPosts = $firebaseArray(querylatestPosts);
console.log($scope.latestPosts) ;
$scope.latestPosts.forEach(function(el) {
if ($scope.checkWorldview(el) == false) {
delete $scope.latestPosts.el ;
}
});
(Note I am unable to log 'el' in the console, nor does the forEach seem to execute, as I can log nothing in the function in the console)
The 'checkWorldview' function behaves as expected when elements are fed in different instances and returns false if the required property is not present in the element under consideration. Thus if the function returns false, I want to delete the specific element in $scope.latestPosts that does not contain the wanted property.
I hope this is clear, thank you in advance for any help you can offer!
The way you are using the $firebaseArray isn't recommended by the docs (see here), which state that $firebaseArray is read only and should not be manipulated.
So you have a few options:
Instead of filtering the array on the client-side, you should modify the query you're using to retrieve data from Firebase to only get elements that have the desired property (ex: use 'equalTo' in the query)
OR
Don't use a $firebaseArray because you're not using it in the way it was intended. Use a regular, good ol' fashion JavaScript array instead.
** Also, just a general comment: don't delete elements from an array as you loop through it as this is generally bad practice (we don't expect arrays to have elements added/removed while we loop through them). Instead, use Array.filter.
I am using linqjs and I have one array full of ids to include in a list, and an array full of complex objects which have a property userId.
Problem is when I do an intersection it never seems to return anything, however there is very little information around the compareSelector.
So here is an example of what I am doing:
enumerableOfUsers.intersect(listOfIdsToInclude, "$.userId");
So in the above example enumerableOfUsers would be an existing enumerable created from an array of users (which contain the userId field), the listOfIdsToInclude is an array of id values, like ["12345", "213213", "2124"] etc.
The intersect seems to work but never returns anything and I know the userIds match so am I doing anything wrong here?
The thing is that the compare selector is applied to items of both the first and second sets. The second set is a list of ids already so the compare selector doesn't apply. The projection yields undefined values which will always result in no results found.
You need to apply the selector only to the first set of values. Try this instead:
// using linqjs 2.x syntax
var query = enumerableOfUsers.Select("$.userId").Intersect(listOfIdsToInclude);
I have a webshop and with jquery i need to check when adding a product if it exists in cart, then it should increase quantity instead of creating a new row.
The code i use to check if it exists in cart is the following:
if ($(".store-purchase-list-quantity-plus").attr('part') != SalesNO)
If this is true, it should add a new row. If its false it should add quantity.
SalesNO is the product id.
This works only for the first product in cart, then it just keeps adding a new row. It seems to me the if statement only checks the first ".store-purchase-list-quantity-plus", even if there are multiple of them in the DOM.
How do i change my if statement so it checks all .store-purchase-list-quantity-plus" after (attr = salesNO)
It's working exactly as it should. That's just not how you expect it to work.
From the documentation:
The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.
There are a number of looping constructs available in jQuery, though given your particular need - finding out if there's an element that has a specific attribute value in a set of matched elements - using .filter() is probably the best choice.
var partExists = $(".store-purchase-list-quantity-plus").filter(function() {
return $(this).attr('part') == SalesNO;
}).length > 0; // there's an element with a part attribute matching SalesNO
if(partExists) {
// increase quantity
}
else {
// add new entry
}
if there are more matches on the page with class store-purchase-list-quantity-plus, you will still only select the first with $(".store-purchase-list-quantity-plus").
Make a loop to check all.
I have a datatable with a number of rows:
var table = $('#mytable').DataTable(...)
And I'm trying to find the rows that contain <a>'s with specific data values.
From the documentation, I'd expect is that table.rows('<magic row-selector>') to work, for some value of <magic row-selector>. But even the simplest selectors don't seem to work the way I'd expect them to.
The docs say that if I pass a string to rows(), it is treated as a JQuery selector operating on the the <tr> elements.
http://datatables.net/reference/type/row-selector
Now I know for certain that each of these rows contains a number of 's - I can see them in the debugger if I examine the outerHTML of the elements returned by table.rows.nodes(). So I'd expect that this would return all rows:
table.rows('a')
But it returns none.
What am I not understanding?
What selector should I use, to find all of the rows that contain <a>'s with a specified value for a data attribute?
edited in response to answer
davidkonrad's answer provides some help - I need to pass a jQuery selector object, rather than a string.
Unfortunately, it seems that I need to construct the jQuery selector object before I define the table. I'm not sure I understand why, it seems an unreasonable restriction, but playing around with his fiddle, I did see differences in the rows returned by table.rows(selector) between when I defined the selector before or after I initialized the table.
In my case, then, that makes this approach unusable, because what I'm trying to do is to remove rows that have certain values set in data attributes. There is no way for me to know what values the user might have selected before I construct the table.
I also think the documentation is a little bit cryptic on that point :) The meaning is
By "jQuery selector" there is meant "the jQuery object returned by a $(selector)"
Only jQuery objects containing <tr>'s is allowed
On paginated tables, you must create the "jQuery selector" before instantiating the dataTable
So, if you want to pass a jQuery object to a dataTables API instance, that contains all rows where any <td> contains the text "test"
var selector = $('tr:contains("test")');
var table = $('#example').DataTable();
var rows = table.rows(selector).data();
//now you can iterate
for (var i=0;i<rows.length;i++) {
//each rows[i] is an array of the rows columns
console.dir(rows[i]);
}
if you want to pass a jQuery object to a dataTables API instance, that contains all rows where any <td> contains an <a> containing a certain text, like "test"
var selector = $('tr a:contains("test")').parent().parent();
...
var rows = table.rows(selector).data();
...
the above selectors in an example -> http://jsfiddle.net/q2p2n23m/
I have a <SELECT multiple="multiple"> box with options.
I store the selected options in a JS variable - selectedFeatures.
I want to pass selectedFeatures array variable of options to jQuery.inArray() - but the function is designed to take and check for one value only.
I can show/hide( or filter ) the markers on my map if I actually specify an index of an element like so: selectedFeatures[0] inside inArray()
..but since I may select multiple options from a select box this method of filtering doesn't work.
How can I check if an array of items in found inside another array with JS/jQuery?
// store selected options as an array of string elements inside the variable
var selectedFeatures = $("#features").val();
// for every element inside 'markers.houses' array...
$(markers.houses).each(function(index, elem){
// check if any of the values inside the 'selectedFeatures' array are found
// also inside a sub-array 'features' inside every element of 'markers.houses'
// array. if 'true' show that particular marker, otherwise hide the marker
if(jQuery.inArray(selectedFeatures, elem.features) !== -1 || jQuery.inArray(selectedFeatures, elem.features) > -1){
markers.houseMarkers[index].setVisible(true);
}else{
markers.houseMarkers[index].setVisible(false);
}
});
Fig 1.1 - store selected options in an array variable and use it with jQuery.inArray()
What you are asking for can be solved with PHP's array_diff function. I know you're not using PHP, but that's why there is array_diff on PHPJS, a project dedicated to porting PHP functions into JavaScript.
Anyway, to solve this you basically want to call array_diff(selectedFeatures,elem.features).length == 0. (You may need to swap the arguments around, I'm not sure which array is which in your question)
array_diff returns the elements of the first array that are not present in the others. If all of the elements in the first array are also in the second array (ie. array1 is a subset of array2), then the returned array will be empty, hence its length is zero.
Check this library: underscore.js
And you could use _.difference(array, *others).
Or you can create your own function to check if values from one array are in another array.