0

I'm generating a link in my javascript

ex. <a href="#" onClick="openContactDetailPage('+JSON.stringify(contact)+')">'+ formattedName + '</a>

However, the quotes aren't escaped in the object so it doesn't really work.

The original link I had was :

<a href="#" onClick="openContactDetailPage('+contact+')">'+ formattedName + '</a><

This just shows the [Object] text not the actual object. I feel like there has to be an easy solution for this I just can't seem to find it.

UPDATE: fixed links to be less generic

2
  • what is object supposed to be? Are you trying to execute a method on the object? if not, what is methodName supposed to do? Commented Jun 22, 2014 at 1:38
  • @mr rogers I'm trying to pass the object to the method methodName. The object is a Contact with name,ID etc. Commented Jun 22, 2014 at 1:40

2 Answers 2

1

You can do the following:

$(document).ready(function(){
    var contacts = {one:'John', two: 'Anne'};  
    for (var prop in contacts) {
        var $anchor = $('<a href=""></a>').text(prop)
        .click(function(e){
            e.preventDefault();
            method({hi:'hi'});
        });
        $('#contacts').append($anchor).append('<br/>');
    }
});

function method(myObject){

    var $response = $('#response');

    for (var prop in myObject) {
        $response.append(prop).append('<br/>');
    }
}

Check this jsfiddle

Sign up to request clarification or add additional context in comments.

1 Comment

I'm generating the href in my javascript dynamically so its not there when the DOM loads. Its basically generating a list of contacts and when the user clicks on one i want to load the detail page for that contact by passing the selected contact object to the method to render it
0
'<a href="#" onclick="methodName('+JSON.stringify(object)+');">Click here</a>'

As you are doing in javascript, it should be string. So you can do like this.

Try this Fiddle

1 Comment

Sorry, this is actually what I have, I updated my question (long day). The issue is the stringify isn't escaping characters so when you see the link this generates it looks like this : onclick="methodName({"id":"001",.. and complains about an invalid { character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.