Basically I'm trying to pass an json-array via onclick to a function
<button
onclick='showAccountOverviewModal("<%= accounts[j].name %>", `<%= accounts[j].bills%>`)'>
Click Me
</button>
But, when I try to parse the string via JSON.parse, I realize, that neither the keys, nor the values have quotation marks. Is there any 'good' way to fix this or do I need to use regular expressions?
Best regards
EDIT
This is the corresponding function:
function showAccountOverviewModal(accountName, accountBills) {
$("#accountModalOverviewTitle").text(accountName);
accountBills = JSON.parse(accountBills);
console.log(accountBills);
accountBills.forEach(bill => {
console.log(bill);
});
}
ill rewrite your code using data-* attribute. you can disregard if you dont want this approach.
html
<button class="showaccountmodal"
data-accountName="<%= accounts[j].name %>
data-bill="<%= accounts[j].bills %>">Click Me</button>
jquery
$(".showaccountmodal").on('click', function() {
var accountname = $(this).data('accountName');
var bill = $(this).data('bill');
console.log(accountname);
console.log(bill);
accountBills.forEach(bill => {
console.log(bill);
});
} );
also here's a reference for storing json object in html Store JSON object in data attribute in HTML jQuery
It looks like you you may be passing a javascript array (already parsed) as opposed to a JSON array (a string representing the array). If so, prior to JSON.parseing it, running
console.log(Array.isArray(accountBills))
should print true. If it is actually JSON, that would print false and running
console.log(typeof accountBills)
would print string.
If it is an array, then you don't need to parse it, and removing the JSON.parse line should make it work as expected.
Related
So i needed to pass a variable to the script tag in the ejs file. it's question array (i called it object in the var name for no reason), that i need to work with in the script tag. i saw that it's done by '<%-varname%>' .
But the thing is, i want to remove stuff from the array while working with it, so i need a copy of this array. And here is the problem:
console.log('<%-passedUser.questionsObject%>')
console.log('<%-passedUser.questionsObject[0]%>')
arrayToUse = '<%-passedUser.questionsObject%>'
console.log(arrayToUse)
console.log(arrayToUse[0])
Output:
question1,answer1,answer2,answer3,answer4,answer5,q2,answer1,answer2
question1,answer1,answer2,answer3,answer4,answer5
question1,answer1,answer2,answer3,answer4,answer5,q2,answer1,answer2
q
I tried JSON.stringify, parse, nothing works. i'd appreciate any help.
Note: i don't know why '<%-passedUser.questionsObject%>' isn't logging the correct way, but it's giving correct values. It's true form is :
[[question1,answer1,answer2,answer3,answer4,answer5],[q2,answer1,answer2]]
you have to use both json parse and json stringify
arrayToUse = JSON.parse('<%- JSON.stringify(passedUser.questionsObject)%>')
later you can easily split the array using
const [questions,answers] = arrayToUse
or do it before sending it to the client
<% const [questions,answers] = passedUser.questionsObject %>
<script>
const arrayToUse = JSON.parse('<%- JSON.stringify(questions)%>')
</script>
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';
}
I appreciate this has been asked numerous times before, as I have just spent the last nine hours reading the questions and answers, over and over, however, I cannot resolve the issue.
I want to pass my php object businessSectors to the html data attribute data-sectors, convert it to JSON, so I can pass it to a javascript function, where I will parse it in to a javascript object.
<td><input type="checkbox" class="minimal"
name="template[]" data-sectors="{{json_encode((array)$template->businessSectors)}}" value="
{{$template->_id}}" {{$template->display ? "checked" : ""}}></td>
Error:
Uncaught SyntaxError: Unexpected token E in JSON at posostion 0 at JSON.parse`
I believe therefore, and correct me if I am wrong, that whatever is being passed to the JSON.parse method is not a valid JSON string.
I've tried therefore to manipulate the value of the data-sectors attribute in my .blade.php in numerous ways, to resolve the issue. I almost certain there is a character that needs escaping but the solution is avoiding me.
Inspecting source gives me:
<input type="checkbox" class="minimal" name="template[]" data-sectors='["Education and
Training"]' value="5d3eb15110560b0a800f359c" >
Could someone please kindly point me in the right direction, and by "point me in the right direction", I mean, please explain in terms that a frustrated layman can understand, exactly what the problem is, and how to go about resolving the issue.
Edit:(Please see the javascript)
<script>
$(document).ready(function(){
let businessSectorData = {!! json_encode($businessSector) !!};
let $businessSector = $("#businessSector");
$businessSector.select2(stdSelect2(businessSectorData));
$businessSector.on("change", function (e) { log("change",e) });
function log (name, evt) {
$("input[name='template[]']").each(function(){
let $this = $(this);
let sectors = JSON.parse($this.data("sectors"));
var i = 0
});
}
})
The jQuery .data() method detects attribute values that look like JSON and parses them automatically. You don't have to call JSON.parse() yourself. The return value of $this.data("sectors") will be an already-parsed JavaScript array.
You have to be careful however about dropping a JSON string into an attribute value, because your serialized value may include single-quote characters. You can escape those easily with a regular expression substitution.
I would recommend base64 encoding the array before adding it to data-sectors. You won't have to worry about unescaped values, and it is a common approach.
You can then decode and parse the array successfully.
Here is an example:
<input
type="checkbox"
class="minimal"
name="template[]"
data-sectors="WyJFZHVjYXRpb24gYW5kIFRyYWluaW5nIl0="
value="5d3eb15110560b0a800f359c"
/>
<script>
(() => {
const element = document.querySelector(".minimal");
const sectors = JSON.parse(atob(element.dataset.sectors));
console.log("data", sectors);
})();
</script>
You can use the PHP function base64_encode() to do the encoding.
This is the HTML attribute:
data-plugin-options="{'Enabled': true, 'StartAt': 30, 'EndAt': 65}"
How can get the value of the keys by javascript by the key name? Such as 'StartAt' value.
Please see below code. we know that singleQuote will give you an error while parsing JSON. so I replace it with doubleQuote.
$(document).ready(function(){
var d=$("#data").attr('data-plugin-options');
d=d.replace(/'/g, '"');
var parsedData=JSON.parse(d);
console.log(parsedData.StartAt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id='data' data-plugin-options="{'Enabled': true, 'StartAt': 30, 'EndAt': 65}">Some text...</p>
Data in element are always a string, but you can parse it, no problem.
Here is an example how to do it
const myElement = document.querySelector('p') // here you have element object, you can use other ways to get it
const dataString = myElement.dataset.pluginOptions // here you have string of the data
const formattedDataString = dataString.replace(/'/g, '"') // your JSON is wrongly formatted, this is fix
const dataObject = JSON.parse(formattedDataString) // where you have object of the data
const dataValue = dataObject.Enabled // where you have value by key
Your JSON is also wrongly formatted, it has single quotes where JSON spec requires double quotes. You can replace it, but this can bring additional problems in case that content contains double quotes - it will crash your script. I'd suggest to look at JSON generation and change it to standard if possible.
Hope this helps
I want to pass Objects as parameters to the javascript function and
I had tried with the following,Actually iam calling the function the function in innerHtml..
var tempObj={
result:results,
jsobj:jsObj
}
str +='<input type="button" onclick="buildCstrWiseChart('+tempObj+')" value="View" class="btn btn-info">';
but this didnt works for me iam getting the error like..
SyntaxError: missing ] after element list
[Break On This Error]
buildCstrWiseChart([object Object])
can any one help in this..
You were treating an object as if it were a string. That's the error.
Is tempObj a global variable? If so, just do
str +='<input type="button" onclick="buildCstrWiseChart(tempObj)" value="View" class="btn btn-info">';`
The string representation of an object is just [object Object] so when you attempt to concatenate it when building your HTML you end up with
onclick="buildCstrWiseChart([object Object])"
which isn't valid HTML. The [object part is parsed as the start of an array, but the Object] part isn't valid array syntax.
I'd suggest, rather than building a HTML string, you instead use jQuery to actually create the DOM element:
$('<input type="button"/>', {
value: 'View',
className: 'btn btn-info'
}).click(function() {
buildCstrWiseChart(tempObj);
});
Then use either the .append() or .appendTo() jQuery function to add that element to whatever containing element you want it to be inside of.
NB: OP has changed the code posted since originally posting.
I'd wager the issue is with this:
...onclick="buildCstrWiseChart('+tempObj+')"...
I don't think that'd work when tempObj isn't something other than a string. Seems dangerous to do in any case.
What you'd really need to do is instead of putting the actual object in the string, put in a value that references it (perhaps build a dictionary of id:object) and just include the id as a data-attribute. Then in your onclick method you can look up that attribute, and find the object for the supplied ID.
Well, the problem is in your function someFunc.
The following example works perfectly fine:
var f = function (el){
alert(el)
};
var x = {a: "hey", b: "ho"};
Then
f('hi');
f(x);
gives no errors.