get array value from get method - javascript

How to get separate values of array in javascript?
in one page:
var c=new Array(a); (eg: a={"1","2"}) window.location="my_details.html?"+ c + "_"; and in my_details.html :
my_details.htm:
var q=window.location.search;
alert("qqqqqqqqqqqqq " + q);
var arrayList = (q)? q.substring(1).split("_"):[];
var list=new Array(arrayList);
alert("dataaaaaaaaaaaa " + decodeURIComponent(list) + "llll " );
But i am not able to get individual array value like list[0] etc
How to get it?
thanks
Sneha

decodeURIComponent() will return you a String; you need to do something like:
var delim = ",",
c = ["1", "2"];
window.location = "my_details.html?" + c.join(delim);
And then get it back out again:
var q = window.location.search,
arrayList = (q)? q.substring(1).split("_"):[],
list = [arrayList];
arr = decodeURIComponent(list).split(delim);
This will use the value of delim as the delimiter to make the Array a String. We can then use the same delimiter to split the String back into an Array. You just need to make sure delim is available in the scope of the second piece of code.

Related

Javascript Multidimensional Array is Empty

I think Im misunderstanding something here - I normally work in PHP and think I'm missing something small. My final array tmp is empty and displays as ",,,,,,,,,,,,,,,,". It seems to me my tmp array might be emptied somewhere or the scope gets reset for some reason. I'm using this as coordinates from a table where you can select table rows and posting to a webservice but my array seem to be erroneous.
var length = $("#arrayCount").html();
var letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var col = getSelectedColumn(); //for example sake lets say "B" is the selected column
var row = getSelectedRow(); //selected rows will be from "11" - "16"
var columnIndexStart = letters.indexOf(col[0]);
var tmp = [];
for(var i = row[0]; i <= row[1]; i++) //rows[0] = 11 and rows[1] = 16
{
tmp[i] = [];
for(var j = columnIndexStart; j < letters.length; j++) //columns and starts at index 1 if we work with "B"
{
var val = $("#" + i + "_" + letters[j]).html(); //using the row and letters as the associated DOM elements ID. Easier to retrieve it's HTML then.
if(val != undefined)
{
console.log("Index [" + i + "]['" + letters[j] + "'] = " + val); //works perfectly and prints as it should.
tmp[i]['"'+letters[j]+'"'] = val; //using quotes to save letters? Is this preferred?
}
}
}
console.log('Final Array: ' + tmp); //empty??
console.log('Final Array: ' + tmp[14]['G']); //testing HTML output. But is undefined.
return tmp;
Any help will be greatly appreciated.
Edited:
Example of console output.
My final array tmp is empty and displays as ",,,,,,,,,,,,,,,,"
With non-numeric index you are setting the field of object and not the element for index.
If you will have two-dimensional numeric array with numeric indices like the following:
var tmp = [[1,2,3], [1,2,3]];
after console.log('tmp = ' + tmp); you will obviously get the output string like:
tmp = 1,2,3,1,2,3
Because when you are trying to convert array to string it converts it elements to string and represent them with a commas.
However when you are trying to set element with non-numeric index, you are setting the field of this object.
var tmp = [];
tmp['A'] = 123;
console.log("tmp = " + tmp); // tmp =
console.log(tmp.A); //123
So, console.log in your case works good - it is serializing all elements of two-dimensional array. But no one array of the second level does not have stored values, it has only fields, which are not included in the string representation of array.
You are getting a set of commas, because each sub-array of tmp array does not contains any element, so it's string representation is an empty string. Each sub-array contains the required data into it's fields.
When you are performing sum operation of string and object you are forcing object to convert to string representation. Instead of this it is recommended to use console.log(yourObj) - it will log the whole object without converting it to string.
//using quotes to save letters? Is this preferred?
No, "A" and A are different identifiers.
var s = new Object();
s['"A"'] = 123;
console.log(s['A']); //undefined
console.log(s['"A"']); //123
Additionally, if you will set fields with quotes - you can not get the field in normal style:
console.log(s."A"); //syntax error : expected identifier after '.'
You can also just do this (use comma, not plus):
console.log('Final Array: ', tmp); //empty??
console.log('Final Array: ', tmp[14]['G']);

Replace value of id in URL

I have URLs of that form:
https://www.merkel.com/obama?trump=15&id=9616071454&hilarry=es
I would like, via javascript to replace 9616071454 with 1, for example.
I know about the replace(), but this will replace "id" itself, not the value of "id".
Is there anything common in the web dev world? :)
The solution considering situations when:
id param can contain other characters besides digits
avoiding fragment # replacement when id is followed by #
var str = 'https://www.foo.com/bar?trump=15&hilarry=es&id=961607some1454text#fragment',
newId = 1,
replaced = str.replace(/\bid=[^&#]+/g, "id=" + newId);
console.log(replaced); // "https://www.foo.com/bar?trump=15&hilarry=es&id=1#fragment"
Simply hard-code that &id= to be re-replaced.
var str = 'https://www.merkel.com/obama?trump=15&id=9616071454&hilarry=es';
var str2 = 'https://www.merkel.com/obama?id=9616071454&trump=15&hilarry=es';
var newId = '123';
str = str.replace(/([&?])id=[0-9]+/, '$1id=' + newId);
str2 = str2.replace(/([&?])id=[0-9]+/, '$1id=' + newId);
alert(str);
alert(str2);
Its simple pattern matching. You can refer to this URL about pattern matching.
function(newValue,url) {
url=url.replace(/id=\d+/,'id='+newValue);
return url;
}
This function works and it allows you to pick way parameter you want.
var exampleStrng ='trump=15&id=9616071454&hilarry=es'; // this is an example query string.
var urlQry = window.document.location.search.substring(1); // you can use this in live code to get the query string.
// reusable function for split in text.
function strSpliter( str, splitVal ){
return str.split(splitVal);
}
// function to reassign query parameter values.
function changQry(qry, setParam, chngVal){
var pnt = strSpliter(qry, '&'),//use the spliter function to change the query into an array split on the '&' character.
newQryArr = [], // a temp array to hold the new parameters and their value.
newQry = '',// this will be the string where the query parameters and values are reconstructed into a string.
newQryStr = '';// this will be the query with the new value.
pnt.forEach( function( item, idx ){
var param = strSpliter(item, '='); //use the spliter function to split the parameter and their value.
// checks the parameter against the one you want to change.
if( param[0] === setParam ){
param[1] = chngVal;// assigns the new value to the parameter.
newQryArr.push(param.join('=')); // rejoins the parameter and its value and pushes it into the temp array.
} else {
newQryArr.push(param.join('='));// rejoins the parameter and its value and pushes it into the temp array.
}
newQry = newQryArr.join('&');// rejoins all the parameters and their values.
newQryStr = '?' + newQry;// creates the new query string.
});
return newQryStr; // returns the new search query string.
}
changQry(exampleStrng, 'id', 77777745);
without comments
var urlQry = window.document.location.search.substring(1);
function strSpliter( str, splitVal ){
return str.split(splitVal);
}
function changQry(qry, setParam, chngVal){
var pnt = strSpliter(qry, '&'),
newQryArr = [],
newQry = '',
newQryStr = '';
pnt.forEach( function( item, idx ){
var param = strSpliter(item, '=');
if( param[0] === setParam ){
param[1] = chngVal;
newQryArr.push(param.join('='));
} else {
newQryArr.push(param.join('='));
}
newQry = newQryArr.join('&');
newQryStr = '?' + newQry;
});
return newQryStr;
}
changQry(urlQry, 'id', 77777745);

Jquery - Create URL from an associative array

I currently have an associative array urlvalue with values as follows:
{"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"}
I would like to turn this array into a URL so that I can send the variables to another page. How can it be done using jquery so that they appear like this:
?folder=subscriber&file=setstatus&alert=yes&id=12
Thanks
You need jQuery.param():
var params = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};
var str = jQuery.param(params);
Use the
$.param(VALUE)
funciton.
Example:
var obj = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"},
toParam= $.param(obj);
alert(toParam);
output:
folder=subscriber&file=setstatus&alert=yes&id=12
Fillder: http://jsfiddle.net/BGjWT/
You can use the map method to turn each key-value pair into a string, then join the array of strings into a single string. Use the encodeURICompontent function to encode the keys and values correctly:
var urlvalue = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};
var param = '?' + $.map(urlvalue, function(v, k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(v);
}).join('&');
alert(param);
Demo: http://jsfiddle.net/Guffa/sCn5U/
You can use the http_build_query() function:
http://phpjs.org/functions/http_build_query/
Try this:
var test = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};
var queryString = "?folder=" + test.folder + "&file=" + test.file + "&alert=" + test.alert + "&id=" + test.id + "";
alert(queryString);
Fiddle
If you don't mind using a plugin, there are some nice ones that do the job.
Possible solution that does not involve jQuery at all (I assume people post jQuery solutions because of the tag):
var combine = function(params) {
var lst = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
lst.push(encodeURIComponent(key)+"="+encodeURIComponent(params[key]));
}
}
return "?"+lst.join("&");
}

Concat JS not working

var myjson = '{"name": "cluster","children": [';
for (var i = 0; i < unique.length; i++)
{
var uniquepart = '{"' + unique[i] + '"';
myjson.concat(uniquepart);
var sizepart = ', "size:"';
myjson.concat(sizepart);
var countpart = count[i] + '';
myjson.concat(countpart);
if (i == unique.length) {
myjson.concat(" },");
}
else {
myjson.concat(" }");
}
}
var ending = "]}";
myjson.concat(ending);
console.log(myjson);
Does anyone know why this string doesn't concat properly and I still end up with the original value?
The concat() method is used to join two or more strings.
Definition and Usage
This method does not change the existing strings, but returns a new string containing the text of the joined strings.
Ref: http://www.w3schools.com/jsref/jsref_concat_string.asp
For example:
myjson = myjson.concat(uniquepart);
OR
myjson += uniquepart;
A javascript string is immutable so concat can only return a new value, not change the initial one. If you want to append to a string you have as variable, simply use
myjson += "some addition";
string.concat() does not modify the original string it instead returns a new string.
In order to modify it you would need to perform:
string = string.concat('fragment');
Strings are immutable.
.concat() returns a new string, which you ignore.

Use "event's" output as a variable

I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});

Categories