to get a list of bools, .contain() - javascript

how do i do a list for bools in javascript. im doing a validation so i can have a list of bools and at the end i want to check that list if it contains any errors. im not sure how to add to the varable validations_errors (like a list). Plus i dont know how i can check if that list contains any true values.
what i got so far is this
var validation_errors;
if (!validateForm($(this))) {
validation_errors = false; //here i want to add the it to a list
var $input_container = $(this).parents('.input');
$input_container.removeClass('success').addClass('error');
}
//this is something what i want to do like (this code is c# based)
if (validation_errors.contains(true)){
// do some actions
}
EDIT
list of bools = list of true & false

validation_errors = []; // DECLARATION
validation_errors.push( newBool ); // adding a new val to the array.
And then you can regularly iterate through the array at the end.
If I were you though, I would try something like this...
validation_errors = false; // declaration
Within the loop
If ( !newBool ) validation_errors = true;
And at the end
If( validation_errors ) //we failed
So you won't need a whole array and a second loop.
Edit : cellphone typing

var validation_errors = [];
.
.
.
if (error) validation_errors.push(true)
if (validation_errors.length > 0) ...
If you want to store true or false so you can use indexOf to find which test failed:
if (validateForm($(this))) validation_errors.push(false);
else {
validation_errors.push(true);
var $input_container = $(this).parents('.input');
$input_container.removeClass('success').addClass('error');
}
var notvalid = validation_errors.indexOf(true);
if (notValid !=-1) alert("The form #"+(notvalid+1)+" failed")

Make validation_errors an array and push the result of your validation into the array. If you don't check for failed validations (i.e. get rid of the ! in your first if statement), the validation_errors array will contain true only if validateForm returns true:
var validation_errors = [];
if(validateForm($(this))) {
validation_errors.push(false);
}
else {
var $input_container = $(this).parents('.input');
$input_container.removeClass('success').addClass('error');
}
if(validationErrors.length > 0) {
//Do some actions
}
Alternatively (as I'm not 100% clear on what you're trying to do), you could just use a string:
var validation_errors = "";
if(validateForm($(this))) {
validation_errors = "true";
}
else {
var $input_container = $(this).parents('.input');
$input_container.removeClass('success').addClass('error');
}
if(validation_errors = "true") {
//Do some actions
}

Related

AngularJS - Programmatically check whether filter exists

Is there a way to programmatically check whether a filter with a given name exists?
I developed a directive to process page content based on a string input, I want it to react differently in case a certain part of the string corresponds to a filter that exists in my system. For example I have a localize filter:
// Somewhere in the code
var myInput = 'localize';
// Somewhere else
var contentToProcess = 'my content';
var result = '';
if ($filter.hasOwnProperty(myInput)) // TODO: this is the part I'm trying to figure out
result = $filter(myInput)(contentToProcess);
else
result = 'something else';
Jonathan's answers is also acceptable, but I wanted to find a way to check if a filter exists without using a try catch.
You can see if a filter exists like this:
return $injector.has(filterName + 'Filter');
The 'Filter' suffix is added by angular internally, so you must remember to add it or you will always return false
Solution
This seems to work for me.
var getFilterIfExists = function(filterName){
try {
return $filter(filterName);
} catch (e){
return null;
}
};
Then you can do a simple if check on the return value.
// Somewhere in the code
var myInput = 'localize';
var filter = getFilterIfExists(myInput);
if (filter) { // Check if this is filter name or a filter string
value = filter(value);
}
Bonus
If you are looking to parse apart a filter string for example 'currency:"USD$":0' you can use the following
var value; // the value to run the filter on
// Get the filter params out using a regex
var re = /([^:]*):([^:]*):?([\s\S]+)?/;
var matches;
if ((matches = re.exec(myInput)) !== null) {
// View your result using the matches-variable.
// eg matches[0] etc.
value = $filter(matches[1])(value, matches[2], matches[3]);
}
Pull it all together
Wish there was a more elegant way of doing this with angular however there doesn't seem to be.
// Somewhere in the code
var myInput = 'localize';
var value; // the value to run the filter on
var getFilterIfExists = function(filterName){
try {
return $filter(filterName);
} catch (e){
return null;
}
};
var filter = getFilterIfExists(this.col.cellFilter);
if (filter) { // Check if this is filter name or a filter string
value = filter(value);
} else {
// Get the filter params out using a regex
// Test out this regex here https://regex101.com/r/rC5eR5/2
var re = /([^:]*):([^:]*):?([\s\S]+)?/;
var matches;
if ((matches = re.exec(myInput)) !== null) {
// View your result using the matches-variable.
// eg matches[0] etc.
value = $filter(matches[1])(value, matches[2], matches[3]);
}
}
You can just do this:
var filter = $filter(myInput);
if (filter)
result = filter(contentToProcess);
else
result = 'something else';
Undefined and null values are treated as false in JS, so this should work in your case.

Remove an object from an from an array by it's id (angular)

I'm trying to remove an object from an array by it's key/value of ID. I would normally just splice by index, however the index might be changing quite a bit because multiple users will be manipulating and updating the object so I want to hook onto something more concrete - aka the id. So I have a bit of logic to check if it still exists and if so remove it by it's ID. However I can't seem to get the syntax quite correct. I Am using underscore.js, I don't know if it's easier with/without it but it's worth mentioning.
Here's what I have -
$scope.toggleSelection = function(typeId,name,index){
//check if exists in array
check = $scope.multipleTypes.some( function( el ) {
return el.name === name;
});
//checked on/off actions
if($scope.items[index].checked == false || $scope.items[index].checked == undefined ){
//IS cecked
if(check){
//already exists, do nothing
}else{
$scope.multipleTypes.push({id:typeId, name:name, checked: true});
}
}else{
//IS not checked
if(check){
var list = _.filter($scope.multipleTypes, function(element){
return element.id != typeId;
}
$scope.multipleTypes = list;
}else{
//is not there, do nothing
}
}
};
So if it does exist and is checked off, it gets pushed. If it does exist and is unchecked, I want to remove it from $scope.multipleTypes by it's ID. I think I Am doing this wrong, all I want to do is remove that one object that has the matching ID from $scope.multipleTypes. Would appreciate any help. Thanks for reading!
If you can use UnderScore Js, You can do it very easily.
Here is an Example:
var someArray= [{Employee:'ved',id:20},
{Employee:"ved",age:25},
{Employee:"p",age:2}];
var a = _.findWhere(someArray,{id:25});//searching Element in Array
var b= _.indexOf(someArray,a);// getting index.
someArray.splice(b,1);// removing.
I normally find the object by id, then splice it out. Note that angularjs adds other properties to the object .
e.g
$scope.items = [......]
var findItemByID = function(id, items){
angular.forEach(items, function(item){
if(item.id === id){
return item;
}
})
return null;
}
var removeItemByID = function(id, items){
var item = findItemByID(id);
if(item){
items.splice(items.indexOf(item), 1);
}
}
//you can now do removeItemByID(id, $scope.items);
//I have not tested this code and it may have syntax errors. hope you get the idea.
Josh

Filter a collection by multiple attributes

I'm using underscore's filter method to retrieve the models I need within a collection. Here's my code so far:
search = {'name':'Jordan', 'country':'Brazil'};
var people = this.filter(function(person){
return person.get('name') == search['name']
&& person.get('country') == search['country'];
});
My problem is, I don't know how many key/value pairs I will receive in the search object. A simple solution would be something like this:
search = {'name':'Jordan', 'country':'Brazil'};
var people = this.filter(function(person){
for(var key in search)
{
if(search.hasOwnProperty(key)) return person.get(key) == search[key];
}
});
But of course it does not work. What can I do?
Edit:
The keys I get in the search object are not necessarily attributes of the models I am filtering. I might receive search = {'name':'Jordan', 'country':'Brazil', 'parentName': 'Steve'};
So one of the filter conditions would be Parents.byID(person.get('parentID')).get('name') == search['parentName'];
Worked it out:
var select = true;
for(var key in search)
{
if(search.hasOwnProperty(key))
{
select = (person.get(key) == search[key]) ? true : false ;
}
if(select == false) break;
}
return select;

get options' value list of a select in an array or JSON without using loop or jQuery each

I need options' value list in an array or JSON.
I have used following code.
var compArray=[];
jQuery("#myCombo option").each(function(){
compArray.push(jQuery(this).val());
});
But i dont want to iterate the options in a loop because my options list can grow.
I have used as
JSON.stringify(document.getElementById("myCombo").options)
But on stringify it shows empty JSON objects, though I can get value from
document.getElementById("myCombo").options[0].value
I have to pass these value in request parameter to server and I do not want to go through the looping.
Please suggest the optimized solution.
You can use custom serializer like this:
var options = Array.prototype.slice.call(document.getElementById("sel").options),
str = JSON.stringify(options, function(key, value){
if(key === ""){
return value;
}
if(!isNaN(parseInt(key))) {
return value.value;
}
};
http://jsfiddle.net/Vh9qD/
Or use iteration without creating jQuery instance for every option
var options = Array.prototype.slice.call(document.getElementById("sel").options),
str = JSON.stringify(options.map(function(item){return item.value;}));
Check this perf test: http://jsperf.com/get-options
But i dont want to iterate the options in a loop because my options list can grow.
This does not have anything to do with the combo.
Whenever you add/delete a option to the combo, just call a function, which will subsequently add/delete that option from your array.
function addDeleteListInArray( oVal, addDelete ) {
if( addDelete ) {
// add to array
compArray.push( oVal );
} else {
// delete from array
for( var i=0; i< compArray.length; i++ ) {
if( compArray[ i ] == oVal ) {
compArray.splice( i, 1 );
break;
}
}
}
}
Hope this helps.

jquery split() issue

Hopefully this is easy for someone.
I have a set of checkboxes with values 1,2,3 etc with the same name attribute (cp_bundle).
I use the following code to get a comma-delimited list of those checkboxes.
var hl_calling_plan_bundle = $('input[name="cp_bundle"]:checked').getCheckboxVal() || "";
jQuery.fn.getCheckboxVal = function(){
var vals = [];
var i = 0;
this.each(function(){
vals[i++] = jQuery(this).val();
});
return vals;
}
if I check the first and third checkboxes, the following will be returned:
1,3
Then, I want to run a test to see whether a particular value (e.g. "3") exists in the the returned variable
But, I can't get past the split of the variable using the following:
var aCallingBundle = hl_calling_plan_bundle.split(",");
This gives the error:
hl_calling_plan_bundle.split is not a function
Any idea what's going on?
hl_calling_plan_bundle is an array. You have to use array operations on it, not string operations.
If you want to know if the value 3 is in the array, then you have to search the array for it. There are many ways to search an array, but since you have jQuery, it's easy to use the .inArray() function:
var index = $.inArray(3, hl_calling_plan_bundle);
if (index != 1) {
// found 3 in the array at index
}
Incidentally, you may want to simplify your function like this:
jQuery.fn.getCheckboxVal = function(){
var vals = [];
this.each(function(){
vals.push(this.value);
});
return vals;
}
or this way:
jQuery.fn.getCheckboxVal = function(){
return(this.map(function(){return(this.value)}).get());
}
split() is a String method, it does not exist on an Array.
When you say the following is returned 1,3, you may be implicitly calling the String's toString() method, which will by default join() the array members with a comma. If you explicitly called toString(), then you could call split(), but that would be an anti pattern.
You don't need to split the string, you can just use RegEx to search:
var str = '1,3,22,5';
/\b1\b/.test(str); // true
/\b2\b/.test(str); // false
/\b3\b/.test(str); // true
/\b5\b/.test(str); // true
/\b22\b/.test(str); // true
Making it a function:
String.prototype.findVal = function(val){
var re = new RegExp('\\b' + val + '\\b');
re.lastIndex = 0;
return re.test(this);
};
str.findVal(2); // false
str.findVal(22); // true
To get the checkboxes:
var cbs = document.getElementsByName('cp_bundle');
To get arrays of all values and the checked values:
var allValues = [];
var checkedValues = [];
for (var i=0, iLen=cbs.length; i<iLen; i++) {
if (cbs[i].checked) checkedValues.push(cbs[i].value);
allValues[i] = cbs[i].value;
}

Categories