I use a ternary operator to check which checkboxes in a form have been selected. If a value has been selected, I affix the name-value pair to a query string which is then passed in an AJAX call. If not, I attach a name with an empty string value.
It works fine, I'm just wondering if there's a more compact/elegant way to do this as it seems somewhat verbose. I'm wondering if it's possible to use a for loop. The reason I'm not sure if this would work is it would involve dynamically assigning variable names within the loop based on the index.
var fields = $('input[name="apn"]').serializeArray();
var apn1 = fields[0] ? fields[0]["value"] : ''
query += '&apn1=' + apn1;
var apn2 = fields[1] ? fields[1]["value"] : ''
query += '&apn2=' + apn2;
var apn3 = fields[2] ? fields[2]["value"] : ''
query += '&apn3=' + apn3;
var apn4 = fields[3] ? fields[3]["value"] : ''
query += '&apn4=' + apn4;
var apn5 = fields[4] ? fields[4]["value"] : ''
query += '&apn5=' + apn5;
...
Map the values and indices to an array of objects, and just pass that directly to $.ajax, jQuery will use $.param on it for you :
var fields = $.map($('input[name="apn"]'), function(el, i) {
var o = {};
o['apn' + i] = el.value;
return o;
});
If its just checkboxes:
$('input[name="apn"]').each(function (i, el) {
if($(el).is(':checked')) {
query += '&apn'+i+'=' + el.value;
}
});
You can simply serialize the form:
var query = $("#FormId").serialize();
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.
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);
});
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.
I'm looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: "malformed URI sequence". If there isn't a jQuery plugin that supports this, I need to know how to modify it to support this.
?search=%E6%F8%E5
The value of the URL parameter, when decoded, should be:
æøå
(the characters are Norwegian).
I don't have access to the server, so I can't modify anything on it.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
Below is what I have created from the comments here, as well as fixing bugs not mentioned (such as actually returning null, and not 'null'):
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:
$.url().param('foo');
If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this:
$.url().param();
This library also works with other urls, not just the current one:
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
It has other features as well, check out its homepage for more docs and examples.
Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null' instead of null, doesn't work with empty parameters (?foo=&bar=x), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.
Use an actual URI parser, don't invent your own.
For those averse to jQuery, there's a version of the plugin that's pure JS.
If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this:
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus would return:
{
date: '9/10/11',
author: 'nilbus'
}
I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too:
Blog post: http://blog.weareon.net/working-with-url-parameters-in-javascript/
Code: http://pastebin.ubuntu.com/1163515/
You can use the browser native location.search property:
function getParameter(paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i=0;i<params.length;i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return unescape(val[1]);
}
}
return null;
}
But there are some jQuery plugins that can help you:
query-object
getURLParam
Based on the 999's answer:
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
Changes:
decodeURI() is replaced with decodeURIComponent()
[?|&] is added at the beginning of the regexp
Need to add the i parameter to make it case insensitive:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}
After reading all of the answers I ended up with this version with + a second function to use parameters as flags
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function isSetURLParameter(name) {
return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href);
return (results !== null) ? results[1] : 0;
}
$.urlParam("key");
For example , a function which returns value of any parameters variable.
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
And this is how you can use this function assuming the URL is,
"http://example.com/?technology=jquery&blog=jquerybyexample".
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');
So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".
You should not use jQuery for something like this!
The modern way is to use small reusable modules through a package-manager like Bower.
I've created a tiny module that can parse the query string into an object. Use it like this:
// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå
There's a lot of buggy code here and regex solutions are very slow. I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple:
/*
* #param string parameter to return the value of.
* #return string value of chosen parameter, if found.
*/
function get_param(return_this)
{
return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.
var url = window.location.href; // Get the URL.
var parameters = url.substring(url.indexOf("?") + 1).split("&"); // Split by "param=value".
var params = []; // Array to store individual values.
for(var i = 0; i < parameters.length; i++)
if(parameters[i].search(return_this + "=") != -1)
return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");
return "Parameter not found";
}
console.log(get_param("parameterName"));
Regex is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. Code source.
<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent(
(location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
);
}
</script>
getURLParameter(id) or getURLParameter(Id) Works the same : )
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
if(arrParamNames[i] == paramName){
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
I created a simple function to get URL parameter in JavaScript from a URL like this:
.....58e/web/viewer.html?page=*17*&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT: 18
Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash.
var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
anchor = hash[1].split('#');
vars.push(anchor[0]);
vars[hash[0]] = anchor[0];
}
}
Slight modification to the answer by #pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.
Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};
This may help.
<script type="text/javascript">
$(document).ready(function(){
alert(getParameterByName("third"));
});
function getParameterByName(name){
var url = document.URL,
count = url.indexOf(name);
sub = url.substring(count);
amper = sub.indexOf("&");
if(amper == "-1"){
var param = sub.split("=");
return param[1];
}else{
var param = sub.substr(0,amper).split("=");
return param[1];
}
}
</script>