Afshin
Afshin

Reputation: 2437

Getting a button ID on click and applying it to a function with javascript

I want to get a button ID onclick and apply it to another function. This is the code I have :

<button id="image-upload-button" onClick="reply_click(this.id)" data-link="<?php echo base_url().'admin/phones/upload_image/'; ?>" input-name="image" on-change="imageUpload(this.form);"></button>

and Javascript :

    //get button id
    function reply_click(clicked_id)
    {
        var button_id = clicked_id;
    }

    function reset() {
        var input_name = $('#' + button_id).attr('input-name');
        var on_change = $('#' + button_id).attr('on-change'); 
        var input = $('<input name="'+ input_name +'" type="file" onchange="'+ on_change +'"/>').appendTo(form);
        input.change(function(e) {
            input.unbind();
            input.detach();
            btn.trigger('choose', [input]);
            reset();
        });
    };

but, when I add $('#' + button_id) whole the script stops working. how can I fix it

Upvotes: 2

Views: 2969

Answers (2)

Radu Cugut
Radu Cugut

Reputation: 1673

you have declared button_id inside the scope of the reply_click() function. You should declare it outside, as a global variable, and just assign it in the reset_click() function.

Upvotes: 3

calebds
calebds

Reputation: 26228

button_id must be visible to reset. Declare it outside:

var button_id;

//get button id
function reply_click(clicked_id)
{
    button_id = clicked_id;
}

Upvotes: 2

Related Questions