Passing Objects as Parameters in javascript function - javascript

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.

Related

JS: Passed JSON-Array loses quotation marks

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.

MVC - reading model variable in jquery

I am trying to read model variable in jquery ready function.
var jsNotes1 =#Model.Notes1;
when the model.notes1 has an integer value, I was having no issues.
But when the model.notes1 has a string value, say for ex: "abcd", the line is getting converted as below
var jsNotes1 = abcd
and Jquery is assuming abcd as a variable rather than as string value and is throwing reference error that abcd is not defined.
Please help me if i am missing something here
try to this
var jsNotes1 ='#Model.Notes1';
You need to wrap it in quotes as it needs to be treated as a string, otherwise it's invalid JavaScript
var jsNotes = "#Model.Notes1";
Try this is in javascript...
var jsNotes1= #Html.Raw(Json.Encode(Model.notes1));

Passing JS Object via HTML string

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/

jQuery - console.log() returns an element but I can't access it

I happened to have super dumb issue and I'm stuck.
I do console.log(data) and I get exactly this:
<a href='http://www.someurl.com'>caption</a>
The question is how do I get this links "href" attribute.
I have absolutely no idea why, but these doesn't work:
data.text() == Uncaught TypeError: undefined is not a function (should be: caption)
$('a',data).attr('href') == undefined (should be: http://www.someurl.com)
Maybe this is not a string, but object or something else? How to check that? My JS looks like this:
window.send_to_editor = function(data) {
var videourl = data;
console.log(videourl.text()); // Uncaught TypeError: undefined is not a function
console.log(videourl); // <a href='http://www.someurl.com'>caption</a>
}
Using jQuery, you can do something like that:
var data = "<a href='http://www.someurl.com'>caption</a>";
var link = $(data).attr('href');
It will create dynamically your DOM element, then you will be able to get your attribute href.
You should first find out, what type data is. To do this you can use the JavaScript builtin function typeof(data).
It's not a jQuery object. That is why it is undefined. First, create a jQuery object.
var _videourl = $(videourl);
console.log(_videourl.text());
console.log(_videourl.attr('href'));
// caption (index)
// http://www.someurl.com
DEMO
In your case, data is a string, not a jQuery object and therefore does not have of jQuery's methods (like text).
If you are certain that data is a string containing a link, you can use a regular expression to extract the link like so:
var match = data.match(/href='(.*)'/g);
url = match && match[1];
console.log(url);
Alternately, you can create a jQuery object from your string. But that's a much more expensive operation if you just want to get the url.

Using JavaScript to bind onclick event with arguments

I am using JavaScript to create a button element and binding onclick event to it. I am using the below code:
function getElement (rowObject )
{
var element ='<div id="deptNmBtn"><button onClick=getDepartMentNm("' + rowObject.empName+'")> <span>Add</span></button></div>';
return element;
}
But here I am passing a parameter Employee Name. The code works if employee name is passed as a single string without any spaces but when passed with spaces its throwing JavaScript error.
SyntaxError: unterminated string literal
Have anyone faced this error? Any help will be really appreciated.
You need to wrap the inline click handler with ':
function getElement (rowObject) {
var element = '<div id="deptNmBtn"><button onClick=\'getDepartMentNm("' + rowObject.empName + '")\' ><span>Add</span></button></div>';
return element;
}
DEMO.
There is a quoting problem in your code. Try this:
var element = '<div id="deptNmBtn"><button onClick="getDepartMentNm(\'' + rowObject.empName + '\')" ><span>Add</span></button></div>';
As you can see, the value for onClick is unquoted. Browsers can parse unquoted attributes, but then they are expected to end up to a space. Actually your parsed code looks like this:
<button onClick=getDepartMentNm("Employer Name")>
HTML parser cuts the function call from the first space, and Name") is ignored since it can't be regognized as valid HTML. JavaScript is executed from "right to left", and the first thing JS tries to do is to get a valid string for function argument. Now HTML parser has cut the function, and JS can't find closing quote, so it throws an error.

Categories

Resources