Reputation: 10239
I have some inputs (checkboxes) and I have the following code:
$(document).on('change', '.my-input', function () {
//I'm doing something here.
});
However few lines above the code I have already selected those checkboxes:
var myInputs = $('.my-inputs');
Is there I way I can reference myInputs
to the listener and use the variable?
PS: Those checkboxes are not in the DOM initially.
Upvotes: 0
Views: 58
Reputation: 4435
Regardless of being in initial DOM state or not, the listener is used the same way. Perhaps consider clearing listeners first as well. The example below listens to change
for an initial set of inputs, unbinds them, adds a new input and re-listens. Also, I've left one input
untouched to show the initial listener state.
Does this help answer your question? I'm unsure whether you are having problems with getting the value of the new elements or just the listener in general. Either way, you can use the new listener to get the checked
state etc.
// Old listener state
$('.inputs, .old-inputs').on('change', function() {
console.log('Input has changed (initial DOM)')
});
// Add a new element to the DOM
$('.inputs-container').append('<input type="checkbox" class="inputs">')
// Unbind
$('.inputs').unbind('change');
// New listener
$('.inputs').on('change', function() {
console.log('Input has changed (post-DOM update)')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='inputs-container'>
<input type='checkbox' class='old-inputs'>
<input type='checkbox' class='inputs'>
<input type='checkbox' class='inputs'>
</div>
Upvotes: 1
Reputation: 6254
You can get the values of selected checkboxes as :
var selectedValues = [];
$(document).on('change', '.my-input', function () {
$. each($(".my-input:checked"), function(){
selectedValues.push($(this).val());
});
});
Upvotes: 0