bhawin
bhawin

Reputation: 285

onchange event on dynamically event

I am creating a input type file and the code is like this

var ele=document.createElement("INPUT");
            ele.type="file";
            ele.id="ele"+i;
            $("#media").append("<br>");
            $("#media").append("<br>");
            $('#media').append(ele);
            $('#ele'+i).on('change',change());
function change()
{
     alert("hello");
}

the problem is that the hello gets alerted when the element is created , why?

Upvotes: 0

Views: 963

Answers (3)

Adil
Adil

Reputation: 148110

You are call method instead of passing handler name.

Change

$('#ele'+i).on('change',change());

To

$('#ele'+i).on('change',change);

You can delegate event to parent using on(), you need to give event handler name i.e change instead of calling it like change(). You can use attribute selector with starts with wild card to bind event to elements having ids like ele*

$('#media').on('click', '[id^=ele]', change);

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery api.

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

Besides what @adil mention,which is the correction to your error, you tagged the question with jquery so you could do

$('<input>', {
  type:'file',
  id: 'ele' + i,
  change: change
}).appendTo('#media');

Upvotes: 1

Barmar
Barmar

Reputation: 780723

This line is incorrect:

        $('#ele'+i).on('change',change());

It should be:

        $('#ele'+i).on('change',change);

You were calling the function instead of passing the function as an argument.

But you shouldn't need to do this after you append each element. Give the new elements a class, and use event delegation:

$("#media").on("change", ".file", change); // Do this just once
function change()
{
     alert("hello");
}

var ele=document.createElement("INPUT");
ele.type="file";
ele.className = "file"
$("#media").append("<br>");
$("#media").append("<br>");
$('#media').append(ele);

Upvotes: 2

Related Questions