Find the index of a dynamically added element
I need to detect which dynamically added checkbox was clicked (either by index, or by name or whatever). Here is a fiddle I found on a familiar question: JSFiddle
I want it to appear as "This is the third checkbox" and not just "clicked". Is it possible?
I tried $(this).index()
it but I had no luck.
+3
source to share
3 answers
First, you can use index()
to get the index of the current element in a consistent set. From this, you can use a helper function to format the ordinal for display. Try the following:
$(document).on('change', '[type=checkbox]', function (e) {
alert('This is the ' + getOrdinal($(this).index('[type=checkbox]') + 1) + ' checkbox');
});
function getOrdinal(n) {
var s = ["th", "st", "nd", "rd"],
v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
+4
source to share
Okay, Rory made it faster. Here's my fiddle for it :)
Html
<button id="append">Append</button>
<div class="wrapper"></div>
<span></span>
Js
var checkbox = $('<input/>', {type : 'checkbox'});
$('#append').click(function(){
$('.wrapper').append(checkbox.clone()).append('checkbox');
});
$(document).on('change', 'input[type=checkbox]', function(){
$('span').text('Index: ' + $(this).index());
});
+1
source to share
Here you are:
var checkbox = '<label><input type="checkbox" />Checkbox</label>';
$(document).on('click', '.add', function () {
$('#group').append(checkbox);
$('[type=checkbox]').checkboxradio().trigger('create');
$('#group').controlgroup().trigger('create');
});
var symbols = {
1: 'st',
2: 'nd',
3: 'rd',
4: 'th'
};
$(document).on('change', '[type=checkbox]', function (e) {
var index = $('[type=checkbox]').index($(this)) + 1;
var symbol = index >= 4 ? symbols[4] : symbols[index];
var str = 'This is the ' + index + symbol + ' checkbox';
alert(str);
});
Hope for this help.
+1
source to share