Search code examples
javascriptjquerycolorbox

How to show JavaScript variable in colorbox


I use colorbox jquery and have problem to show variable in colorbox.

I have variable called wp_store_caption that get value from input type :-

<input type="text" id="title" class="ab_form_text wp_store_caption require" name="wp_store_caption" value="">

Now i use colorbox like :-

jQuery(document).ready(function() {
    var wp_store_caption = jQuery('#title').val();
    jQuery(".open-popup-link").colorbox({html:"<h1>"+wp_store_caption+"</h1>"});

});

But canot show value of wp_store_caption, But when use alert() without colorbox, I can see the value.

Where is problem ?!


Solution

  • It is not happening because when you write

    jQuery(".open-popup-link").colorbox({html:"<h1>"+wp_store_caption+"</h1>"})
    

    you bind the value of wp_store_caption, which is initially not defined.

    You need to bind click event and assign value to wp_store_caption, and then call colorbox function.

    You should write this:

    $(".open-popup-link").click(function () {
        $.colorbox({
            html: "<h1>" + $('#title').val() + "</h1>"
        });
    });
    

    See DEMO here.

    In this example, I have predefined value of title. Please note this value will not update the heading in colorbox because the value of -wp_store_caption is not being updated.