Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a string in onclick function's attribute of element dynamically created element

I am trying to pass a string in the onClick event handler function's arguments of the dynamically created anchor element, see the fiddle http://jsfiddle.net/shmdhussain/bXYe4/.

I am not able to pass the string to the function, but i am able to pass the number integer to the function. Please help me in this. Thanks in advance.

html:

<DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>test</title>
        <link rel="stylesheet" href="mystyle.css" class="cssfx"/>

        <script src="/jquery.min.js"></script>
        <script src="colon.js"></script>
    </head>

    <body>

        <div class="mytest">

        </div>


    </body>
</html>
</html>

Javascript:

var elem=[  {"name":"husain","url":"http://google.com","age":21},
            {"name":"ismail","url":"http://yahoo.com","age":22},
            {"name":"nambi","url":"http://msn.com","age":23}
         ]

jQuery(function($){
    var str="";
    for(i=0;i<elem.length;i++){
        str+="<a href='#' onclick='test('"+elem[i].url+"')'>dd</a><br><br>"
        console.log(str);

    }
    $('.mytest').html(str);

});

function test(url){
    console.log("url is "+url);
}
like image 687
Mohamed Hussain Avatar asked Apr 16 '13 11:04

Mohamed Hussain


People also ask

Can we pass parameter in onclick function?

If your button is generated dynamically: You can pass string parameters to JavaScript functions like the below code: I passed three parameters where the third one is a string parameter.

Does Onclick work on any element?

The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.

How do you pass a function on onclick event?

To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .

What does onclick attribute do?

The onclick event attribute in HTML works when the user clicks on the button. When the mouse clicked on the element then the script runs. Attribute Value: This attribute contains a single value script that works when the mouse clicked on the element.


1 Answers

You have to use proper string sytax. This

"<a href='#' onclick='test('"+elem[i].url+"')'>dd</a><br><br>"

will result in

<a href='#' onclick='test('http://domain.tld')'>dd</a><br><br>

You cannot use ' for onclick and the parameters of test. Use \" instead.

"<a href='#' onclick='test(\""+elem[i].url+"\")'>dd</a><br><br>"

Which results in

<a href='#' onclick='test("http://domain.tld")'>dd</a><br><br>
like image 142
AmShaegar Avatar answered Oct 15 '22 08:10

AmShaegar