user3806279
user3806279

Reputation: 23

Passing global variable in javascript to live event on jquery does not work

I have created several elements dynamically in javascript. These are, among others, range inputs. I want on "input change" event to show the value. Each of these inputs have id like 'probabilitate'+number. The number is a global variable, and is incremented on click event of a button.

When I create dynamically these inputs, the input change event does not work anymore. There is a question on stackoverflow, in which the solution is live event, not on event, and it works, partially. The code is:

 $(document).on('change','#probabilitate'+nrBoli, function(){

      //something
  })
The problem is that if the event is triggered on '#probabilitate1' (for example) event, the variable nrBoli works fine inside the function, but if I want to concatenate it with the name for id as parameter (my case, to trigger for each element), nrBoli is unavailable.

Upvotes: 1

Views: 357

Answers (1)

Jamilson Junior
Jamilson Junior

Reputation: 29

You need to use 'class' instead 'id' to get all elements. Using 'id' you get only the first element in the DOM:

Append elements:

var globalProp = 1;

$("#sameContainer").append('<input type="checkbox" id="inputId" class="probabilitate' + globalProp + '"/>');

Set change event:

The change event must be set whenever new elements is appended.

$('.probabilitate' + globalProp).change(function () {
    //do action
})

Example:

var globalProp = 1;

function appendInput(){
    $("#sameContainer").append('<input type="checkbox" id="inputId_a" value="check this" class="probabilitate' + globalProp + '"/>');
    $("#sameContainer").append('<input type="checkbox" id="inputId_b" value="or this" class="probabilitate' + globalProp + '"/>');
    $("#sameContainer").append('<input type="checkbox" id="inputId_c" value="or this" class="probabilitate' + globalProp + '"/>');

    $('.probabilitate' + globalProp).change(function () {
        //do action
    })
};

Hope this helps.

Upvotes: 0

Related Questions