escaped URL parameters statements if else switch - javascript

There is a little problem with this code:
function getParameters() {
var searchString = document.getElementById('input1').value,
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]);
}
console.log(hash);
//return hash;
if(val[0] == "class"){ //alert(val[1]);
$.each(hash, function( attribute, value ) {
test_div.setAttribute(attribute,value);
});
}
else if(val[0] == "color"){ //alert(val[1]);
$.each(hash, function( attribute, value ) {
test_div.style[attribute]=value;
});
}
monitor_test_div.innerText = ccc.innerHTML;
}
Depending by the order in which the parameters are inserted, they are repeated or dont work...
style a div using escaped URL parameters
Demo: JSFiddle 1
Demo: JSFiddle 2
I would like to obtain this:
Example 1:
input:
opacity=0&src=link1&color=red&color=green&src=link2&height=200
output:
<div src="link2" style="color: green;"></div>
Example 2:
input:
src=link1&color=red or color=red&src=link1
output:
<div src="link1" style="color: red;"></div>

in your line
if(val[0] == "class")
you are only checking the first element in your val array.
what you would want to do, is iterate through all the hash objects and simply check the attribute like this:
function getParameters() {
var searchString = document.getElementById('input1').value,
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]);
}
console.log(hash);
//return hash;
$.each(hash, function( attribute, value ) {
if(attribute=="color"){
test_div.style[attribute]=value;
}
else if(attribute=="src"){
alert(attribute);
test_div.setAttribute(attribute,value);
}
});
}
here is a working FIDDLE

Maybe you want something like this:
var test_div = $('#test_divs_id');
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
var key = unescape(val[0]);
var val = unescape(val[1]);
switch(key) {
case 'class': // treat 'class' key by ...
test_div.addClass(val); // ... adding the value as a class
break;
case 'src': // treat 'src' key,
case 'href': // treat 'href' key, maybe more ...
test_div.attr(key, val); //... by adding as an attribute with value
break;
default: // all other keys...
test_div.css(key, val); // ... are assumed css style names with value
break;
}
EDIT: Extended the switch with the examples + possibly more attributes

Related

JavaScript Check multiple variables being empty

I'm trying the following code:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array('var1','var2','var3');
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
The result here should have been count = 2 because two of the variables are empty but it's always 0. I guess it must something when using if (field_is_empty(name)) because it might not getting the name converted to the name of the actual var.
PROBLEM 2# Still related
I've updated the code as Karthik Ganesan mentioned and it works perfectly.
Now the code is:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
And the problem is that if add a new if statement something like this:
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(name,"test");
}
}
}
It does nothing and I've tested using variableService.setValue('var1',"test") and it works.
PS: The variableService.setValue is a function controlled by the software I don't know exactly what it does I know if use it like mentioned on above line it works.
In your first attempt you used the variable names as strings when you created an array. You need to either use the values themselves:
vars = new Array(var1,var2,var3);
or if you insist to use them by their names, then you need to find them by names when you use them:
if (field_is_empty(window[name])) {
It does nothing
That's not really possible. It could throw an error, or enter the if or enter the else, but doing nothing is impossible. However, since you intended to use the variables by name in the first place (probably not without a reason) and then you intend to pass a name, but it is a value and it does not work as expected, I assume that your initial array initialization was correct and the if should be fixed like this:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]]; //You need the value here
if (field_is_empty(v)) {
count++;
}
}
console.log(count);
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]];
if (field_is_empty(v)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(vars[i],"test");
}
}
}
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
You definitely incorrectly initialize array, you put strings "var1", "var2", "var3" instead of references to strings (variables).
Try this:
vars = new Array(var1,var2,var3);
Your array is wrong
it should be
vars = new Array(var1,var2,var3);
here is the jsfiddle

replace anchor tag href with variable from url string javascript

I have following java script code:
var product = getQueryVariable("product");
$('a.link').each(function()
{
$(this).attr("href", $(this).attr("href") + "&product=" + getQueryVariable("product"));
});
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var variables = query.split("&");
for (var iCount = 0; iCount < variables.length; iCount++)
{
var pair = variables[iCount].split("=");
if (pair[0] == variable)
return pair[1];
}
}
If url is: http://www.xxxx.com/index.htm?product=abc, It sets a link to an anchor tag
<a class="link" href="http://www.aaaa.com/index.htm">Click here</a>
as
<a class="link" href="http://www.aaaa.com/index.htm?product=abc">Click here</a>
which is what I want, and it does it well.
But if anchor tag already has product variable in its href like
<a class="link" href="http://www.aaaa.com/index.htm?product=xyz">Click here</a>
then I get
<a class="link" href="http://www.aaaa.com/index.htm?product=xyz&product=abc">Click here</a>
while I was expecting that if product variable is present in href of anchor tag, it will replace existing product variable. And if there is no product variable in href tag, it will append it.
The code appends well, but does not replace existing product variable in href of anchor tag.
So, the question is how do I get 'product' param from all a tags that have class 'link'? so that I can replace it in my code if found. And can I fetch it in $('a.link').each(function() ?
How can I do it?
Try this,
Array.prototype.contains = function(x){
return this.indexOf( x ) > -1 ? true : false;
}
var getUrlVars = function(url){
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
}
if(vars[0] == url){
vars =[];
}
return vars;
}
var getUrl = function(url){
var urlParams = getUrlVars(window.location.href),
linkParams = getUrlVars(url),
altered = false;
for(i = 0; i < linkParams.length; i++){
var t = linkParams[i];
if(urlParams.contains(t)){
linkParams[t] = urlParams[t];
altered = true;
}
}
return altered ? url.split("?")[0] + "?" + linkParams.map(function(y){return y + "=" + linkParams[y]}).join("&") : url;
}
$("a.link").each(function (i,link) {
link.attr("href",getUrl(link.attr("href")));
})
Try this
$('a.link').each(function()
{
$(this).attr("href", $(this).attr("href").split("product=")[0] + "product=" + getQueryVariable("product"));
});
This works with links already containing product value
You can do something like this:
function changeLinkQueries(link,parameter,replacedVal) {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = link.split('?')[1];
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
var queries = query_string,
linkArr = [];
queries[parameter] = replacedVal;
for(query in queries){
linkArr.push(query + '=' + queries[query]);
}
return link.split('?')[0] + '?' + linkArr.join('&');
};
The function usage is : changeLinkQueries(link,parameter,replacedVal):
link : is the link that you want to modify
parameter: the parameter you want to change
replacedVal: the value that you want to replace with it
Example: changeLinkQueries('http://www.aaaa.com/index.htm?product=xyz','product','test') returns ==> http://www.aaaa.com/index.htm?product=test
Add this function to your code and update your code to :
var product = getQueryVariable("product");
$('a.link').each(function(){
$(this).attr("href", changeLinkQueries($(this).attr("href"),'product',getQueryVariable('product')));
});
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var variables = query.split("&");
for (var iCount = 0; iCount < variables.length; iCount++)
{
var pair = variables[iCount].split("=");
if (pair[0] == variable)
return pair[1];
}
}
This code worked:
$('a.link').each(function()
{
var anchor_url = $(this).attr("href");
var product_val = '';
if (-1 == anchor_url.indexOf('&product='))
{
if (-1 == anchor_url.indexOf('?product='))
product_val = anchor_url.substr(anchor_url.indexOf('?product=')+'?product='.length);
}
else
product_val = anchor_url.substr(anchor_url.indexOf('&product=')+'&product='.length);
if (product_val.indexOf('&') != -1) product_val = product_val.substr(0, product_val.indexOf('&'))
if (product_val == '') new_link = anchor_url+'&product='+getQueryVariable("product");
else new_link = anchor_url.split(product_val).join(getQueryVariable("product"));
$(this).attr("href", new_link);
});
i hope this will help,
$(this).attr("href", getQueryVariable($(this).attr("href"), "product"));
function getQueryVariable(hrefLink, variable)
{
if(hrefLink.contains("product")){
return hrefLink;
}else{
//write your code here and return full url
}
}

Can this function be re-written recursively or more cleanly?

This function match sets an attribute (collapsed) to true or false depending on
the value of a string :
function match(children) {
var data = $scope.treeData
for (var i = 0; i < data.length; i++) {
var s = data[i]
for (var i2 = 0; i2 < s.children.length; i2++) {
var s2 = s.children[i2]
for (var i3 = 0; i3 < s2.children.length; i3++) {
for (var i4 = 0; i4 < s2.children[i3].children.length; i4++) {
var text = "";
if ($scope.searchText == undefined) {
text = ""
} else {
text = $scope.searchText
}
if (s2.children[i3].children[i4].label
.toLowerCase() === text.toLowerCase()) {
s2.children[i3].collapsed = false
}
}
}
}
}
}
Excluding the bad use of variable names i3,i2 etc is there a cleaner method ?
As the inner most loop requires access to the outer loop can recursion still be used ?
Update :
Data structure :
[{"label":"test","collapsed":false,"children":[{"label":"test","collapsed":false,"children":[],"$$hashKey":"002"}],"$$hashKey":"001"}]
Update 2 :
Using a recursive function but the string 'test' is not being matched :
http://jsfiddle.net/U3pVM/19196/
fiddle src :
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
</div>
</div>
function TodoCtrl($scope) {
var json = [{"label":"test","collapsed":false,"children":[{"label":"test","collapsed":false,"children":[],"$$hashKey":"002"}],"$$hashKey":"001"}]
var searchText = 'test'
function match(node, searchText){
angular.forEach(node.children, function(idx, child){
node.collapsed = child.label.toLowerCase === searchText.toLowerCase
console.log(node.collapsed)
if(child.children.length > 0){
match(child, searchText);
}
});
}
match(json, searchText);
}
Please try this :
function match2(obj) {
if (obj.children) {
for (var i = 0; i < obj.children.length; i++) {
match2(obj.children[i]);
}
}
else {
var text = $scope.searchText ? $scope.searchText : "";
if (obj.label
.toLowerCase() === text.toLowerCase()) {
obj.collapsed = false
}
}
Your JSFiddle is very nearly there. I made a couple of changes for this working JSFiddle.
First, you were passing an array into match and not an object. I changed your json variable to be json instead by removing the outer [], but you could also have fixed this by passing in json[0].
The other change was that you had the two parameters, child and idx, were the wrong way round.
function match(node, searchText){
angular.forEach(node.children, function(child, idx){
node.collapsed = child.label.toLowerCase === searchText.toLowerCase
console.log(node.collapsed)
if(child.children.length > 0){
match(child, searchText);
}
});
}
Here's another way of doing it, using some:
function match (node, searchText) {
node.collapsed = node.children.some(function(child) {
return child.label.toLowerCase === searchText.toLowerCase;
});
angular.forEach(node.children, function(child, idx){
match(child, searchText);
})
}
I think something like this may work for you. I don't know anything about angular there might be something there that would make it easier.
var searchText = ($scope.searchText == undefined) ? "": $scope.searchText;
match($scope.treeData, searchText);
function match(node, searchText){
$.each(node.children, function(idx, child){
node.collapsed = child.label.toLowerCase === searchText.toLowerCase
if(child.children.length > 0){
match(child, searchText);
}
});
}

Split array by tag and delete all similar element

I have some html page with text and need to output all inner HTML from tag b by alphabetical order in lower case. I'm just a begginer, so don't be strict.
My code is here (text is just for example): http://jsfiddle.net/pamjaranka/ebeptLzj/1/
Now I want to: 1) save upper case for inner HTML from tag abbr; 2) delete all similar element from the array (as MABs).
I was trying to find the way to split the array by tag, but all that I've done is:
for(var i=0; i<allbold.length; i++){
labels[i] = allbold[i].innerHTML;
}
var searchTerm = ['abbr'];
var abbr = [];
var keywordIndex;
$.each(labels, function(i) {
$.each(searchTerm, function(j) {
var rSearchTerm = new RegExp('\\b' + searchTerm[j] + '\\b','i');
if (labels[i].match(rSearchTerm)) {
keywordIndex = i;
for(var j=0; j<labels.length; j++){
abbr[i] = labels[i];
}
}
});
});
Vanilla JS solution (no library required, see jsFiddle):
var allbold = document.querySelectorAll("b"),
words = document.querySelector("#words"),
labels = {}, i, word, keys, label;
// first, collect all words in an object (this eliminates duplicates)
for(i = 0; i < allbold.length; i++) {
word = allbold[i].textContent.trim();
if (word === 'Labels:') continue;
labels[word.toLowerCase()] = word;
}
// then sort the object keys and output the words in original case
keys = Object.keys(labels).sort();
for(i = 0; i < keys.length; i++){
label = document.createTextNode("SPAN");
label.textContent = labels[keys[i]];
words.appendChild(label);
// add a comma if necessary
if (i < keys.length - 1) {
words.appendChild(document.createTextNode(", "));
}
}
with one helper:
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, "");
};
jQuery solution (see jsFiddle):
$(".content b").map(function () {
return $("<span>", {text: $.trim(this.textContent)})[0];
}).unique(function () {
return lCaseText(this);
}).sort(function (a, b) {
return lCaseText(a) < lCaseText(b) ? -1 : 1;
}).appendTo("#words");
with two helpers:
$.fn.extend({
unique: function (keyFunc) {
var keys = {};
return this.map(function () {
var key = keyFunc.apply(this);
if (!keys.hasOwnProperty(key)) {
keys[key] = true;
return this;
}
});
}
});
function lCaseText(element) {
return element.textContent.toLowerCase();
}
use the mapping element Is THIS FIDDLE for all upper case else this fiddle after your comment what you need
var maplabels = [];
for(var i=0; i<allbold.length; i++){
if (allbold[i].innerHTML != "Labels:") {
if(maplabels.indexOf(allbold[i].innerHTML) == -1){
maplabels.push(allbold[i].innerHTML);
labels.push('<i>' + allbold[i].innerHTML.toUpperCase() + '</i>');
}
}
}

How to dynamically access nested Json object

I am trying to populate my input fields based on the retrieved JSON object. The field names in my form would be something like:
fullName
account.enabled
country.XXX.XXXX
The function should return something like below for the above fields
aData["fullName"]
aData["account"]["enabled"]
aData["country"]["XXX"]["XXXX"]
How should I write my a function that returns a matching JSON entry for a given HTML field's name ?
you could use the attached method that will recursively look for a given path in a JSON object and will fallback to default value (def) if there is no match.
var get = function (model, path, def) {
path = path || '';
model = model || {};
def = typeof def === 'undefined' ? '' : def;
var parts = path.split('.');
if (parts.length > 1 && typeof model[parts[0]] === 'object') {
return get(model[parts[0]], parts.splice(1).join('.'), def);
} else {
return model[parts[0]] || def;
}
}
and you can call it like that :
get(aData, 'country.XXX.XXXX', ''); //traverse the json object to get the given key
Iterate over the form elements, grab their names, split on '.', then access the JSON Object?
Something like:
var getDataValueForField = function (fieldName, data) {
var namespaces = fieldName.split('.');
var value = "";
var step = data;
for (var i = 0; i < namespaces.length; i++) {
if (data.hasOwnProperty(namespaces[i])) {
step = step[namespaces[i]];
value = step;
} else {
return (""); // safe value
}
}
return (value);
};
var populateFormFields = function (formId, data) {
var fields = document.querySelectorAll('#' + formId + ' input');
for (var i = 0; i < fields.length; i++) {
fields[i].value = getDataValueForField(fields[i].name, data);
}
};
populateFormFields('myForm', fetchedFromSomeWhere());

Categories

Resources