Having problems passing a JS object to a JS method via an HTML String. Here's a part of the HTML String:
onclick='addGrpMember("+c+"); return false;'
When I click to invoke this method I see this: Unexpected identifier
I can easily pass in properties of this c Object a la:
onclick='addGrpMember(\""+ c.contactName +"\",\""+ c.displayName +"\"); return false;'
And that works just fine.
What am I missing here? By the way, "c" is passed into the method as an arg. (where I'm executing this code).
Thanks for any helpful tips!
Updated with full code:
contact = "<tr><td style='width:60px; padding:12px 6px' title='"+ c.contactName +"'><span class='contactAvatar'><img src='<%= context %>/app/user/image?loginName="+ c.contactName +"' alt='' /></span></td><td style='padding-top:12px'><span class='contactTitle'>"+ c.displayName +"</span><br/><span class='contactTitleCompany'>"+c.title+ " at " +c.companyName+"</span><br/><a href='mailto:"+c.contactName+"'><i class='icon-envelope'></i> "+c.contactName+"</a></td><td style='padding-top:30px;padding-right:10px;text-align:right'><a href='#' data-toggle='tooltip' data-placement='right' title data-original-title='Add Member' onclick='addGrpMember("+c+"); return false;' class='addIcon'></a></td></tr>";
And the method:
function addGrpMember( c ){
selectedGroup.members.push( c );
populateSearchResults( selectedGroup.members, 'groups' );}
You will need to convert c into a JSON string. Assuming you are making this string in JavaScript.
onclick='addGrpMember("+JSON.stringify(c)+"); return false;'
JSON.stringify is IE 8+.
With that said... there is probably a better way to do what you are trying to do, but without seeing your entire method we can't really comment on that much. Generally inline JavaScript isn't the way to go.
I think , no need to concat the string or extract the object elements, all you need is to put this code on the button event onClick
onclick='addGrpMember(c); return false;'
if c is your javascript object
It should work just passing in the object variable name:
<button onClick="addGrpMember(c);">Add Group Member</button>
Then in your JavaScript, something like:
var c = {
contactName : "value1",
displayName : "value2"
};
var addGrpMember = function (groupMember) {
// Do something with the group member
return false;
};
Here is a working fiddle with some similar code: http://jsfiddle.net/vgF8C/
Related
In laravel, my controller returns this collection, as you can see, it has another collection evidences as relations. How do I separate or use this collection. What I am already doing is in this code snippet below.
template: function (row) {
console.log("in return: ", row.evidences))
return '\
<a href="javascript:;" class="btn btn-sm btn-clean btn-icon btn-icon-md"
title="Show details" \
data-toggle="modal" data-target="#showModal" data-id="' + row.id +
'" data-title="' + row.title +
'" data-description="' + row.description +
'" data-evidencedata="' + row.evidences+
'">\
<i class="la la-eye"></i>\
</a>\
';
},
Now if I use console.log(row.evidences) in the above function before return statement it prints out the content that it holds and the type of row.evidences is Object because of which I can iterate through it and use it. Now the problems is when I try to access this evidences collection in another jquery function, I could not.
I am accessing it in this code snippet below
$('#showModal').on('show.bs.modal', function (event) {
let button = $(event.relatedTarget);
let id = button.data('id');
let modal = $(this);
modal.find('form input#title').val(button.data('title'));
modal.find('form textarea#description').val(button.data('description'));
console.log("in show: ", button.data('evidencedata'))
});
It also changed its type from Object to String which could not let me iterate through it. I have tried JSON.stringify() and JSON.parse() but no result but I am able to access other data which I am sending along with it i.e. title and description.
What am I doing wrong here. Am I missing something?
title and description are working because they are already plain strings. You are defining a string of html text for your button. Any variable you use is turned into a string as well.
Since your evidencesdata is an object, this won't work correctly. You have 2 options:
1. Turn the object into json, than base-encode it (to avoid problems with quotes). Later you can base-decode it, and parse the json, and you'll have the object again.
2. Don't return a button string, but define a button object, and use the data functions to add the object to the button. (using jQuery $("<button>").data(evidencesdata))
The second is probably better, in terms of JavaScript internals and objects in memory, but might impact your code more than the first option.
Yes! the problem was with the object-string. It was being converted to string as data was being passed in data-template. So the simple solution to this problem was to convert the Object which is in my case is row.evidences to String using JSON.Stringify(row.evidences) and adjust the double and single quotes accordingly and then wherever I want to use that simply button.data('evidencesdata'), and use it using forEach or whatever.
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.
I have a problem, i have to call a function from a button onclick().
Javascript :
function deleteFolder(elemento){
var form=document.getElementById(elemento);
var conf=confirm("Sei sicuro di eliminare questa cartella?\nL'eliminazione sara' definitiva");
if (conf === true)
form.submit();
}
This function get a paramater made by php ,the pRoblem is that if this parameter has some space inside, the function is not called ..
deleteFolder(FolderName) --> It works
deleteFolder(Folder Name) --> of course it doesnt works
From php i just scan directories and put names of them in multiple form with foreach() function.
So the question is :
1) How from php i can put parameter that works with calling javascript's function with spaces inside?
2) If i have a directory called "Folder's name", it's enough put addslashes in $_POST to bypass XSS? because it cut all next the apostrophe and became :
HTML
<button onclick="deleteFolder(Folder)">
Thanxs for any suggestions, i can't find anything similar already in this forum.
I am assuming that you are passing a string to the deleteFolder() method. If that is the case, use the following code.
<button onclick="deleteFolder('FolderName')">
<button onclick="deleteFolder('Folder Name')">
You should use quotes to indicate that you are passing a string to the function. This should fix your problem.
You can put the actual folder name in a separate attribute say folder-name and in the id have incremental numbers, with this being in place following change would be needed in your JavaScript function.
HTML
<button folder-name="Folder" onclick="deleteFolder(id)">
JavaScript
function deleteFolder(elemento){
var form=document.getElementById(elemento);
var folderName = form.getAttribute('folder-name');
// then use the folderName however you want it.
}
Thanxs to all replies ! =)
I solve it adding " (--> " ) in php
first
"<button onclick='deleteFolder(".$elem."); return false;'>Elimina</button>"
next
"<button onclick='deleteFolder("".$elem.""); return false;'>Elimina</button>"
So the parameter became a string and can be passed to the function =)
The code looks something like this:
<?php
$page->startscript();
echo "
function f1(id){
$('#def').html('<button class=\'btn btn-danger\' onclick=\'f2(id);\'>act</button>');
}
function f2(id){
alert(id);
}
";
$page->endscript();
?>
The startscript(), endscript() thing works fine, it just allows me to add JS to the page. What doesn't work is id isn't carried over from f1 to f2, its just returning blank. I think it has something to do with the quotes and not being treated as a variable. If I pass an int as the parameter for the onclick attribute it works fine.
Variables aren't expanded inside strings in Javascript (ES6 adds "template strings", which support this), you need to use concatenation. And assuming id is a string, you need to put quotes around it in the function call.
echo"
function f1(id){
$('#def').html('<button class=\'btn btn-danger\' onclick=\'f2(\"' + id + '\");\'>act</button>');
}
function f2(id){
alert(id);
}
";
It's got to do with the context of your f2 function.
Since the function isn't present on the page, the scope in which the rendered JS is looking can't really find the function you've declared.
I've created a basic fiddle that shows you how you can achieve what you're looking to do here. JSFiddle
Basically, your js will call the f1 function like so:
function f1(id) {
$('#def').append('<button class="btn btn-danger" onclick="f2(' + id + ');">act</button>');
}
f1("10");
your HTML will need to look something like this:
<div id="def">
</div>
<script>
function f2(id){
alert(id);
}
</script>
Also, the JS that you're rendering is literally passing in the id to f2 as a string and not the value.
Hopefully you can see what you need to do.
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.