Store a jQuery selector into a string and use it - javascript

The jQuery selector I want to store in a string variable named "jQuerySelector" in Java is :
$('h3.icon').parents('.head').find('h5:contains(Input)')
Then use it as follows:
String result = "return $(\"" + jQuerySelector + "\").get(0);";
I am facing syntax error when I initialized "jQuerySelector" as follows and run:
String jQuerySelector = "('h3.icon').parents('.head').find('h5:contains(Input)')";
My only requirement is to store the above selector query into a string and use it for running the above return statement.
Can anybody help me out please?

Related

How do I create a custom javascript variable that selects part of an already existing javascript variable?

I am trying to create a custom javascript variable in GTM that returns part of a javascript variable that already exists.
Variable that already exists: window.ShopifyAnalytics.meta.product.variants.0.name
returns this: "Bamboo Basic String - Schwarz - S"
However I want to code a custom javascript variable to just return the Schwarz part, is this possible? If so what is the code that I would need?
Please can someone let me know what code to put into GTM to create this variable?
TIA
If all names are pretty much the same you could use split to get that part of string and then remove whitespaces. It would look like this:
window.ShopifyAnalytics.meta.product.variants.0.name.split('-')[1].replace(/
/g,'');
If the already existing variable is always structured the same way you could do something like this:
let variable = window.ShopifyAnalytics.meta.product.variants.0.name.split('-')
Then by calling varaible[1] you get the 'Schwartz' part of the variable.
If you want a return value you can use a function like the following and call it wherever you want.
Simply make sure to pass the correct argument content
// Declaring a function getColor that returns the second element in the list,
// trimmed (without spaces before and after)
const getColor = (content) => {
return content.split('-')[1].trim();
}
const test = "Bamboo Basic String - Schwarz - S";
console.log(getColor(test));
//console.log(getColor(window.ShopifyAnalytics.meta.product.variants.0.name));
You could split the string on the hypens (-) like this:
const productName = window.ShopifyAnalytics.meta.product.variants.0.name;
const part = productName.split(' - ')[1];
Assuming you have a consistent format, and you always want the second part after that hyphen.
split will separate parts of a string into an array where it finds a match for the argument. The first index [0] will be the product name, the second [1] will be the part you're looking for.
This could cause issues if you have a product name with a - in it too though so use with care!
If it needs to be an anonymous function for GTM, you could try the following (though I'm not a GTM expert):
function () {
const productName = window.ShopifyAnalytics.meta.product.variants.0.name;
return productName.split(' - ')[1] || 'Unknown';
}

Using a variable as a classname

I am trying to put a class name stored in a variable into my JQuery where I want the class to be, this should change which class is affected depending on the parameter passed through the URL query string.
I have built the class name and stored it in the 'param' variable as below.
var param = '".' + "proj" + location.search.substring(6) + '"';
$(param).css('display', 'inline');
And want to change the css on the class inside of it but this does not seem to work for me. Perhaps because it tries to change the css of the variable rather than what is inside of it.
If not how can I solve this or if so, is there a better way I could go about this?
You're confusing a string literal to be only enclosed by double quotes ", while that is not the case. Remove them
var param = '.' + "proj" + location.search.substring(6);
Set the param variable as the location substring (assuming that this substring is correctly getting the desired result from your URL) - then use that in the jQuery by joining with the common portion as follows.
var param = location.search.substring(6);
$('.proj' + param).css('display', 'inline');
You will need to ensure that a) you have the jQuery library and b) you have the jquery code wrapped in a $(document).ready(function(){}) wrapper.
Also - its usually better to add / remove a class rather than directly affecting the CSS in the jquery
var param = location.search.substring(6);
$('.proj' + param).addClass('displayInline');
//CSS
.displayInline{display: inline}

Init jQuery function and pass a variable with a string

Hardcoded i would initilize (a plugin in this case) like so, which is working:
var cal = $("#calendar").calendario({
caldata : {
'09-11-2015_1':['09-11-2015',0,19]
}
});
Now i want to pass the caldata option a variable with the content like that:
var init_events = $("#init_events").val();
var cal = $("#calendar").calendario({
caldata : init_events
});
init_events has the value {'09-11-2015_1':['09-11-2015',0,19]}
But that doesnt work. If I log the output of the option inside the plugin it just returns a string in the console where as if I log the first Code it logs an Object.
I tried jQuery.parseJSON(init_events) but this returns an Unexpected token error.
Any idea how i could get this working with passing a variable?
init_events is not valid JSON. JSON only allows double quotes around strings, not single quotes, so it should be:
{"09-11-2015_1":["09-11-2015",0,19]}

Output JavaScript from Razor

I have an ASP.NET MVC app. One of the views in my app has some JavaScript. I want to set the value of a JavaScript variable based on a value in the ViewBag. If the ViewBag value exists and is not null, I want to use it. Otherwise, I want to assign an empty string value to the JavaScript variable. Here's what I'm currently trying:
<script type='text/javascript'>
function formatItem(item) {
var itemName = #(ViewBag.ItemName ? ViewBag.ItemName : '');
alert(itemName);
}
</script>
This block throws an error that says:
Compiler Error Message: CS1011: Empty character literal
Is there a way to do what I'm trying to do? If so, how?
Thanks!
You just need to use an empty string instead of a character literal (double quotes versus single quotes):
<script type='text/javascript'>
function formatItem(item) {
var itemName = '#((!string.IsNullOrEmpty(ViewBag.ItemName)) ? ViewBag.ItemName : "")';
alert(itemName);
}
</script>
Your only real problem was that you used '' instead of "". '' Means a character, "" means a string;
You need double quotes and not single quotes.
var itemName = '#(String.IsNullOrEmpty(ViewBag.ItemName) ? ViewBag.ItemName : "")';
even better you might want to use the String object:
var itemName = '#(String.IsNullOrEmpty(ViewBag.ItemName) ? ViewBag.ItemName : String.Empty)';

How do I retrieve nodes with one or another value with XPATH

I have a javascript function that needs to retrieve certain nodes through xpath using document.evaluate, till now I am using something like
.//span[contains(#title, 'alerting')] | .//span[contains(#title, 'caution')]
But it turn in a very long string when values to match are more. I cannot use [#title = word], because I need to retrieve the elements whose atributes contains some string. I have tried things like
.//span[contains(#title, ('alerting'|'caution'))]
But it does not retrieve anything.
Can you give me an idea to shorten the first sintax?
Why not just create a function that creates the string and build the expression programmatically, and not worry about it? Roughly:
function spanContains(s) {
return ".//span[contains(#title, '" + s + "')]";
}
var contains = [spanContains('word1'), spanContains('word2')].join("|");
You could also try using matches instead of contains, although I'm not sure what the JavaScript syntax for that would be, or if it's supported.
XPath should be this way:-
.//span[contains(#title, 'alerting') or contains(#title, 'caution')]
.//span[contains(#title, ('alerting'|'caution'))]
This is invalid XPath -- the union operator | can only have arguments that are node-sets -- not strings.
Use:
.//span[#title
[contains(.,'alerting')
or
contains(.,'caution')
]
]
Instead of using document.evaluate(), you could use jquery in which case you could do:
$('span').filter(function() {
var title = $(this).attr('title');
return title != undefined && title.search(/(alerting|caution)/) != -1;
});

Categories

Resources