Cusmar Cusmar - 5 months ago 6
jQuery Question

jQuery : $("#id") doesn't work in a function

I've a problem with my jQuery function.

This code works:

$("input.read_picture").on('keyup', function () {
$("#load_picture").attr('src', $(this).val());

$("#load_picture").error(function(){
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});

$("#show_picture").css('display', 'block');
});


But when I want to store my function not into my jQuery event, it doesn't work. Nothing displays.

Here is the code that doesn't work:

function changePicture(url) {
$("#load_picture").attr('src', url);

$("#load_picture").error(function(){
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});

$("#show_picture").css('display', 'block');
}

$("input.read_picture").on('keyup', changePicture($(this).val()));


Thanks for your help!

Answer

This,

$("input.read_picture").on('keyup', changePicture($(this).val()));

will call the function as soon as handler is loaded.

Use a callback,

$("input.read_picture").on('keyup', function(){
    changePicture($(this).val())
});
Comments