1

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.

1
  • Can you create a plunkr to reproduce the issue? Commented Nov 12, 2015 at 14:26

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.