Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a javascript function within dynamically created html

I have a javascript file as you'll see in picture below .
In this file i create a html code for my webpage , And In this html i call a function defined in the javascript file . But when i run it i get that the function isn't defined .
additional info :

http://s8.postimg.org/nqwv1na6d/js_function.png

http://s1.postimg.org/mqyu5zalr/js_function.png

plus the function mentioned ("cButton") is defined in another function inside the javascript file.

(function () {
    var thecid = 0;

    function cButton (ii) {
        document.getElementById(ii).style.display = 'none';
        alert('fdgfg');
    }

    $("#subber").on("click", function () {
        var thelm = "#c0"+thecid;
        var newcommhtml = '<div id="c0' + thecid + '" class="cnew clearfix">';
        var ii='c0'+thecid;
        newcommhtml += '<section class="c-content">';
        newcommhtml += '<a href="#" onclick="cButton(\'' + ii + '\');" style="color:black;">x</a>';
        newcommhtml += '<p>' + nl2br(textval) + '</p> </section></div>';        
    });
})()
like image 431
saeed hardan Avatar asked Jul 26 '26 00:07

saeed hardan


2 Answers

For the onclick to work, you need your cButton() to be accessible globally as a property of the global window object.

Change you code to:

window.cButton = function(ii) {
   ...
}
like image 192
techfoobar Avatar answered Jul 27 '26 17:07

techfoobar


The problem is that you are defining cButton inside the document ready handler, so it doesn't exist outside that. If you declare the function outside then things can access it later...

function cButton(ii){
    document.getElementById(ii).style.display = 'none';
    alert('fdgfg');
}

(function(){
    var thecid = 0;
    $("#subber").on("click", function(){
        var thelm = "#c0"+thecid;
        var newcommhtml = '<div id="c0'+thecid+'" class="cnew clearfix">';
        var ii='c0'+thecid;
        newcommhtml += '<section class="c-content">';
        newcommhtml += '<a href="#" onclick="cButton(\''+ii+'\');" style="color:black;">x</a>';
        newcommhtml += '<p>'+nl2br(textval)+'</p> </section></div>';        
    });
})()
like image 44
Reinstate Monica Cellio Avatar answered Jul 27 '26 19:07

Reinstate Monica Cellio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!