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;
}
Related
I have an array in JavaScript like this
var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
when I alert in JavaScript it gives as below
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
But I want like this which is duplicates removed array
var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
On alert it should give like this
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
First Thing your array contains string as a constant that's not going to work.
Secondly, if all of you value are strings you can do it as follows:
var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"];
var uniqueArray = data.filter(function(item, pos) {
return data.indexOf(item) == pos;
})
alert(uniqueArray);
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:
var data [/* ... */];
var unique_data = [];
for(let i = 0; i < data.length; i++) {
if (data[i] && unique_data.indexOf(data[i]) === -1) {
unique_data.push(data[i]);
}
}
Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().
You can create your unique function to remove duplicate entry and empty value from array like this.
var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"]
var unique_data = uniqueList(data);
alert(unique_data);
function uniqueList(list) {
var uniqueResult = [];
$.each(list, function(i, e) {
if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value
uniqueResult.push(e);
});
return uniqueResult ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have the following array:
etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest
I want to delete the value of an input box from the array, here's what I'm trying:
var el = document.getElementById('searchInput').value; // this is "test"
var toSearchFor = eld.slice(0,10); // the array above
for(var i=0; i < toSearchFor.length; i++) {
toSearchFor[i] = toSearchFor[i].replace(/el/g, "");
}
It's simply not replacing "test" with ""
How can I do that?
You can use Array.filter (see MDN) to filter out the desired value:
var arr = 'etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest'.split(',')
,val = 'test'
document.querySelector('#result')
.innerHTML = arr.filter(function (v) {return v != val});
<div id="result"></div>
A text field example in this jsFiddle
for global replacement of a string stored in a variable u need to create an instance of RegExp explicitly, like this:
var regex = new RegExp(el, "g");
then use it in replace function:
toSearchFor[i] = toSearchFor[i].replace(regex, "");
The problem with your code is in your regular expression: /el/g. This is trying to match the letters el, instead of whatever it's in the el variable. You could have done it using the RegExp construtor.
// ...
regexp = new RegExp(el); // No need to use 'g' here since you're looking for the whole word
toSearchFor[i] = toSearchFor[i].replace(regexp, "");
// ...
Here's another way of doing it:
var eld = ['etst','tset','tets','ttest','teest','tesst','testt','4est','test','dest'];
// var el = document.getElementById('searchInput').value;
var el = 'test';
console.log(eld);
var index = eld.indexOf(el);
if (index >= 0) {
eld[index] = '';
}
console.log(eld);
Here's the output:
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "test", "dest"]
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "", "dest"]
In this case, we're using Array.prototype.indexOf, which returns the first index at which a given element can be found in the array, so that we can access that element directly (if found).
I hope that helps!
I need to save all the color values of the elements in the pages of my site and put them in a database. I thought I'd do it this way:
First thing I'm going to pick up the rgb values of each element so
$("*").each(function(e){
createColorArray($(this).css('backgroundColor'));
});
then in the function createColorArray store into an array all the values that are passed
function createColorArray(rgbColor)
{
//Create rgb array
}
and finally remove duplicate items from my array
function removeDoupe(ar) {
var temp = {};
for (var i = 0; i < ar.length; i++)
temp[ar[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
now my question is,
how recommended to create the array? directly inside the $ ("*") or in a dedicated function as I'm thinking? also i need than once removed duplicates in the new array "clean" as well as the rgb value I would have also given the number of times that value was in the original.
Some example code?
As I mentioned in the comments, why not check for duplicates earlier? A simple example:
var colors = [];
$('*').each(function(i, el){
var $element = $(el),
color = $element.css('background-color');
if(!~$.inArray(color, colors))
colors.push(color);
});
console.log(colors);
http://jsfiddle.net/sL9oeywk/
The best way to do this is to do it all while you are working on it. Heres a way you could potentially do it:
var colors = new Array();
var tempColors = {};
$(".colors").each(function(){
var c = $(this).val();
// check if the color exists without looping
if(typeof tempColors[c] == "undefined"){
// if it doesn't, add it to both variables.
tempColors[c] = true;
colors.push(c);
}
});
This will result in two variables: one is an object that you don't have to loop through to find out if you defined it before, one is a colors array that you push to using standard javascript.
You shouldn't make it a dedicated function if you are not reusing it, but you could make it an object like this:
var colors = function(){
var self = this;
self.array = new Array();
// this is a dedicated check function so we don't need separate variables.
// returns true if the color exists, false otherwise
self.check = function(color){
for(var i =0; i < self.array.length; i++){
if(self.array[i] === color) return true;
}
return false;
}
self.add = function(color){
// use the check function, if it returns false, the color does not exist yet.
if(!self.check(color)){
self.array.push(c);
}
}
}
You can then instantiate a colorlist using var colorlist = new colors(); and add colors using colorlist.add("dd0300"). Accessing the array can be done by requesting colorlist.array.
I have some code I want to put into a JSON object ultimately. But first I want to create a javascript object and within that object add an array of values. Sounds simple enough but my approach seems wrong. First I create a basic object, the set a few fields. Lastly, iterate over a bunch of checkboxes and then, if one is checked at that value to an array.
At the last step I need to add that array to my object (myData) and then JSONify it.
Any ideas how I can do this, seems myData.push(filters); doesn't work...
Note that the object itself is not an array, I want to place an array IN the object.
var myData = new Object();
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
var i=0;
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters[i] = {
filterIds: $(this).val()
};
++i;
}
});
myData.push(filters);
That's not how to add items to an Object, change
myData.push(filters);
to
myData.filters = filters;
Also, maybe change = new Object to = {}. There's no difference, but it's easier to read, because literal notation takes up less space.
Read more about Array.prototype.push
Use push to add elements to the filters array. Use property assignment to add another property to the myData object.
var myData = {
deviceId: equipId,
dateTo: dateTo,
dateFrom: dateFrom,
numResults: $("#numResults").val()
};
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters.push({
filterIds: $(this).val()
});
}
});
myData.filters = filters;
BTW, don't use new Object() to create an object, use {}.
Remove the need for an extra array and i.
var myData = {}
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
myData.filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
myData.filters.push({
filterIds: $(this).val()
});
}
});
I'm trying to break up a string like this one:
fname=bill&mname=&lname=jones&addr1=This%20House&...
I want to end up with an array indexed like this
myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] =
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House
The url is quite a bit longer than the example. This is what I've tried:
var
fArray = [],
nv = [],
myarray = [];
fArray = fields.split('&');
// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push(nv[0],nv[1]);
nv.length = 0;
}
The final product is intended to be in 'myarray' and it is, except that I'm getting a one dimensional array instead of a 2 dimensional one.
The next process is intended to search for (for example) 'lname' and returning the index of it, so that if it returned '3' I can then access the actual last name with myarray[3][1].
Does this make sense or am I over complicating things?
Your line myarray.push(nv[0],nv[1]); pushes two elements to the array myarray, not a single cell with two elements as you expect (ref: array.push). What you want is myarray.push( [nv[0],nv[1]] ) (note the brackets), or myarray.push(nv.slice(0, 2)) (ref: array.slice).
To simplify your code, may I suggest using Array.map:
var q = "foo=bar&baz=quux&lorem=ipsum";
// PS. If you're parsing from a-tag nodes, they have a property
// node.search which contains the query string, but note that
// it has a leading ? so you want node.search.substr(1)
var vars = q.split("&").map(function (kv) {
return kv.split("=", 2);
});
For searching, I would suggest using array.filter:
var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });
NB. array.filter will always return an array. If you always want just a single value, you could use array.some or a bespoke searching algorithm.
for (var i = 0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push([nv[0],nv[1]]);
}
nv.length = 0; is not required, since you're setting nv in each iteration of the for loop.
Also, use var i in the for-loop, otherwise, you're using / assigning a global variable i, that's asking for interference.