0

I have an object that I need to pass to a function, this function is trigger via onClick and onKeyUp(), but I couldn't make it work.
Although I can pass values to it.

function myFunc(myObj) {

 $("<button type="button" onclick='otherFunction( $(\"#elem\").val() )'
onkeyup='otherFunction( $(\"#elem\").val() )'> CLICK IT </button>"
} 

As you can see, i have a otherFunction and I Can pass the $("#elem").val() as a parameter. But I need to also pass myObj to it.
Tried everything I could think of and I was unable to make it work.

Obs: myObj is a marker from googleMaps, so I can't just pass it's attributes values. I need to access the full object on my second function. Because I need to do something like: myObj.setOptions(.....)

2
  • I think your script is not proper so if you write it clearly then i can help you. Commented Feb 21, 2018 at 12:22
  • @pankaj98 Not sure how to do that. It's a javascript function that uses jquery to create a button with onclick and onkeyup in it. And I'm having difficult passing the parameter because it's an object and not just a string. Commented Feb 21, 2018 at 12:24

2 Answers 2

3

As you are using jQuery to create button, use .on() to bind event handler's. The object myObj will be accessible in the event handler due to closure

function myFunc(myObj) {
    var button = $('<button>', {
            "type": "button",
            "text": "CLICK IT"
        }).on('click keyup', function () {
            // myObj will be accessible here
            otherFunction($("#elem").val());
        });
}

A good read How do JavaScript closures work?

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

3 Comments

may I normally pass the myObj to the function ? Like: otherFunction($("#elem").val(), myObj);
Amazing ! I'm just having some trouble to append it to another object using appendTo(). Is it possible to do something like button.appendTo($('myDiv')); ?
@PlayHardGoPro, Yes mate, provided you have an myDiv element
2

this code explained how you send data to the handler with jQuery

$('yourElement').click(yourData, function(eventObject){
    var thisIsYourData = eventObject.data;
})

Comments

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.