user911
user911

Reputation: 1559

Passing argument to on click event of dynamically generated element

I am trying to pass arguments to onclick event of dynamically generated element. I have already seen the existing stackoveflow questions but it didn't answer my specific need.In this existing question , they are trying to access data using $(this).text(); but I can't use this in my example.

Click event doesn't work on dynamically generated elements

In below code snippet, I am trying to pass program and macroVal to onclick event but it doesn't work.

onClickTest = function(text, type) {
        if(text != ""){
        // The HTML that will be returned
        var program = this.buffer.program;
        var out = "<span class=\"";
        out += type + " consolas-text";
        if (type === "macro" && program) {
            var macroVal = text.substring(1, text.length-1);
            out += " macro1 program='" + program + "' macroVal='" + macroVal +  "'";
        }
        out += "\">";
        out += text;
        out += "</span>";
        console.log("out " + out);


        $("p").on("click" , "span.macro1" , function(e)
        {
            BqlUtil.myFunction(program, macroVal);
        });

    }else{
        var out = text;
    }
    return out;

};

console.log of out give me this

<span class="macro consolas-text macro1 program='test1' macroVal='test2'">{TEST}</span>

I have tried both this.program and program but it doesn't work.

Upvotes: 0

Views: 208

Answers (1)

Igor
Igor

Reputation: 15893

Obtain values of span element attributes, since you include them in html:

$("p").on("click" , "span.macro" , function(e)
{
  BqlUtil.myFunction(this.getAttribute("program"), 
    this.getAttribute("macroVal"));
});

There are, however, several things wrong in your code.

  • you specify class attribute twice in html assigned to out,

  • single quotes you use are not correct (use ', not ),

  • quotes of attribute values are messed up: consistently use either single or double quotes for attribute values

var out = "<span class='";

...

out += "' class='macro' program='" + program + "' macroVal='" + macroVal + ;

...

out += "'>";

  • depending on how many times you plan to call onClickTest, you may end up with multiple click event handlers for p span.macro.

Upvotes: 1

Related Questions