Discover the position of a dynamically added element

Is there a way to identify the specific dynamically added checkbox that was clicked, whether by index or name? I came across a similar question with a solution in this JSFiddle: JSFiddle

Instead of just displaying "clicked", I would like it to show something like "This is the 3rd checkbox". Is this achievable?

I attempted to use $(this).index(), but so far I have not been successful.

Answer №1

One way to find the position of an element within a set is by using the index() method. By utilizing a helper function, you can then format the number as an ordinal to display. Here's an example:

$(document).on('change', '[type=checkbox]', function (e) {
    alert('You have selected the ' + getOrdinal($(this).index('[type=checkbox]') + 1) + ' checkbox');
});

function getOrdinal(num) {
    var suffix = ["th", "st", "nd", "rd"],
        val = num % 100;
    return num + (suffix[(val - 20) % 10] || suffix[val] || suffix[0]);
}

Check out this fiddle for reference

Answer №2

Well, Rory managed to optimize it even further. Check out the updated fiddle here :)

Your HTML code:

<button id="append">Append</button>
<div class="wrapper"></div>
<span></span>

Javascript changes:

var checkbox = $('<input/>', {type : 'checkbox'});

$('#append').click(function(){
    $('.wrapper').append(checkbox.clone()).append('checkbox');
});

$(document).on('change', 'input[type=checkbox]', function(){
    $('span').text('The index is: ' + $(this).index());
});

Answer №3

Here is the code snippet for adding and manipulating checkboxes:

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);
});

I hope this information proves to be useful for your project.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve data using the designated key and convert it into JSON format

If I have the following JSON array: [ {"data": [ {"W":1,"A1":"123"}, {"W":1,"A1":"456"}, {"W":2,"A1":"4578"}, {"W":2,"A1":"2423"}, {"W":2,"A1":"2432"}, {"W":2,"A1":"24324" ...

Vue.js is not properly synchronizing props in a child component when the parent component is updating the property

When it comes to communication between components, my structure looks something like this: <div id=chat-box> <div class="wrapper"> <div> <chat-header></chat-header> <message-container :chat="chat"></message ...

I am facing issues with getting the delete function to properly function in my React

Issue with Delete Button Functionality in React While I am able to successfully delete an item using axios call in Postman, implementing the same functionality on the front-end in a React component seems to be causing problems for me. <button onSubmit ...

Various placements in Internet Explorer, Chrome, and Mozilla Firefox

Currently, I am working on a website project The layout appears to be fine in Internet Explorer and Firefox, but there seems to be an issue in Chrome. Due to the length of the code, it cannot be posted here, so I have included links to the files: HTML: ...

unique array that shuffles every time it is reloaded, utilizing only javascript

I have created a string array that holds 6 different classes. Whenever I click a button, a new class is generated randomly. However, the issue arises when I click the button again and get the same class instead of a new random one. Even after reloading the ...

Peculiar redirection encountered while handling a form with checkbox option

When I try to submit the form in Chrome, the PHP file does not get called and I am redirected to another HTML page. However, in Firefox, when I select three checkboxes, it redirects me to that same HTML page as in Chrome. I even tried using radio buttons i ...

React: Submit button not triggering form submission despite having a valid submit event handler and correct syntax

My question stands out from existing ones as it features valid syntax, correct use of type="submit" on the button, and a simple onSubmit handler on the form. Despite this, clicking the button fails to trigger the onSubmit handler. To illustrate ...

Div element positioned outside of another div element

I hate to bug you with more css issues, but I'm really struggling with this one. The problem I'm facing is that a sub div is overflowing the boundaries of its parent div. I tried using: display: inline-block;` but then the outer div goes haywir ...

How can I use a combination of attributes selector in jQuery?

Is there a way to achieve this using jQuery? $('#SomeId input[type="hidden" AND name="somename"]') ...

Why opt for ref.current over directly applying the condition?

I'm curious as to why the code uses if (ref.current && !ref.current.contains(event.target)) rather than if (!ref.current.contains(event.target) function useOutsideAlerter(ref) { useEffect(() => { // Function for click event function hand ...

My form submission is getting messed up by VueJS, causing it to delete all of the data

It seems that VueJS is causing issues with my form submission process, as it is removing the post data from the Ajax serialize() function. I suspect it could be due to the combination of using Ajax and Jquery, but I'm unsure how to resolve this issue ...

Implement CSS to layer HTML 5 canvases while including a margin

I have a design conundrum in my app where I am using multiple stacked HTML canvas elements for drawing. My goal is to make the canvases fit perfectly within their containing div while also maintaining a left and bottom margin. This is how my HTML structur ...

Struggling with implementing a materialize modal?

I am encountering a problem with Materialize. This time, I am trying to create a modal div, but it doesn't seem to be working. The button is created, but when I click on it, nothing happens. I have made sure to link all the necessary Materialize files ...

Error with the login component in React.js (codesandbox link included)

Hey there! I'm a beginner programmer and I recently dove into a tutorial on creating a Login Form. However, I've run into a few issues along the way. Overview of My Project: The login form I'm working on was built using create-react-app. T ...

Concealing option value based on ng-if conditions in AngularJS: A guide

I am designing an Input form with two input fields that need to be compared and values displayed if a certain condition is met. The input fields are: <td class="td_label"><label>Client Age :</label></td> <td class="td_input"> ...

Utilize a CSS style or class on a div element

Looking for a way to style alternate div elements within a parent div? Check out this example: <div id="comment"> <div id="m1">...</div> <div id="m2">...</div> </div> I tried to use some jQuery to add a CSS c ...

Route all Express JS paths to a static maintenance page

Need help with setting up a static Under construction page for an Angular Web App with Express Node JS Backend. I have a function called initStaticPages that initializes all routes and have added a new Page served via /maintenance. However, when trying to ...

Using jQuery to remove the last two characters from a specified class

I have a simple task at hand. I am trying to use the slice method in JavaScript to remove the last two characters from a string that is generated dynamically within a shopping cart. Instead of displaying a product as $28.00, I want it to display as $28. S ...

Problem arises when attempting to display a div after clicking on a hyperlink

I'm encountering an issue with displaying a div after clicking on a link. Upon clicking one of the links within the initial div, a new div is supposed to appear below it. All tests conducted in jsfiddle have shown successful results, but upon transf ...

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...