Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 991067
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T06:02:51+00:00 2026-05-16T06:02:51+00:00

I have a loop that when it is called, creates a div with some

  • 0

I have a loop that when it is called, creates a div with some form elements in them. Each div is based on a variable, “i” to give unique names to the fields and divs. Is there a way I can store what the variable was at the point of creating the div?

For example, div1 is created and everything in it has 1 (the variable) attached to the name. The form elements rely on each other and are called by ID. Problem is, when I create a new div and the variable (i) is changed to 2, the first set of form elements try to use 2 instead of 1.

Make sense?

Edit: Here’s some code. It’s pretty messy so I apologize in advance.

    var i = 0;

    $('a#add-product').click(function(event){
        i++;
        $('<div />').addClass('product').attr('id', 'product'+i)
            .append($('<h2><img src="<?php echo base_url();?>img/product.png" alt="" />Product '+i+'</h2>'))
            .append($('<div class="info-line"><label>Division</label><p><select id="selection-'+i+'" class="selection"><option value="">- Select a Division -</option><option value="abrasives">Abrasives</option><option value="tapes">Bonding, Surface Protection &amp; Tapes</option><option value="packaging">Packaging</option></select></p></div>'))
            .append($('<div class="info-line"><label>Category</label><p><select id="selectionresult-'+i+'" name="selectionresult-'+i+'" class="selectionresult"></select><span id="result-'+i+'" class="result">&nbsp;</span></p></div>'))
            .append($('<div class="info-line"><label>Product</label><p><select id="selectionresult2-'+i+'" name="selectionresult2-'+i+'" class="selectionresult2"></select><span id="result2-'+i+'" class="result2">&nbsp;</span></p></div>'))
            .append($('<a class="remove" href="#add-product" id="remove-product'+i+'"><img src="<?php echo base_url();?>img/remove-product.jpg" alt="" />Remove Product</a>'))
            .appendTo("#products");

            // START OF ADDITIONAL PRODUCT DROP DOWNS

                    $("#selectionresult-"+i).hide();
                    $("#selectionresult2-"+i).hide();

                    $("#selection-"+i).change( function() {

                        $(this).next(".selectionresult").hide();
                        $(this).next(".selectionresult2").hide();
                        $("#result-"+i).html('Retrieving ...');
                        $.ajax({
                            type: "POST",
                            data: "data=" + $(this).val(),
                            url: "<?php echo base_url();?>dropdown.php",
                            success: function(msg){
                                if (msg != ''){
                                    $("#selectionresult-"+i).html(msg).show();
                                    $("#result-"+i).html('');
                                }
                                else{
                                    $("#result-"+i).html('<em>No item result</em>');
                                }
                            }
                        });

                    });
                    $("#selectionresult-"+i).change( function() {
                        $(this).next(".selectionresult2").hide();
                        $("#result2-"+i).html('Retrieving ...');
                        $.ajax({
                            type: "POST",
                            data: "data=" + $(this).val(),
                            url: "<?php echo base_url();?>dropdown.php",
                            success: function(msg){
                                if (msg != ''){
                                    $("#selectionresult2-"+i).html(msg).show();
                                    $("#result2-"+i).html('');
                                }
                                else{
                                    $("#result2-"+i).html('<em>No item result</em>');
                                }
                            }
                        });
                    });
    });
  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T06:02:51+00:00Added an answer on May 16, 2026 at 6:02 am

    You can place the code that needs to reference the correct version of i in a closure like this:

    var i = 0;
    
    $('a#add-product').click(function(event){
        i++;
    
        // Begin closure. When called (at the end of the closure) it receives
        //    the current value of "i". This value of "i" will be referenced
        //    throughout the closure as a local variable containing the value
        //    you expect, instead of the "shared" "i" variable outside the 
        //    closure.
        (function( i ) {
    
            // So basically we've created a new "scope" inside here. Now "i"
            //    is a separate local variable than the "i" variable ouside
            //    the closure. You could change the variable name by changing
            //    the parameter above. Like (function( my_i ) {...
            // If you did that, you would need to change the "i" in your .change()
            //    handlers to "my_i". The rest of them could stay the same, or you
            //    could change them. Either way would work.
            // This is because the .change() handlers are executed at a later time
            //    (and so are the AJAX callbacks) so they need to use the variable
            //    that is local to this closure.
            // The rest of the code, like $("#selectionresult-" + i) is executing
            //    immediately, so it could reference the "i" variable that is
            //    outside the closure, and still work properly.
    
            $('<div />').addClass('product').attr('id', 'product'+i)
                .append($('<h2><img src="<?php echo base_url();?>img/product.png" alt="" />Product '+i+'</h2>'))
                .append($('<div class="info-line"><label>Division</label><p><select id="selection-'+i+'" class="selection"><option value="">- Select a Division -</option><option value="abrasives">Abrasives</option><option value="tapes">Bonding, Surface Protection &amp; Tapes</option><option value="packaging">Packaging</option></select></p></div>'))
                .append($('<div class="info-line"><label>Category</label><p><select id="selectionresult-'+i+'" name="selectionresult-'+i+'" class="selectionresult"></select><span id="result-'+i+'" class="result">&nbsp;</span></p></div>'))
                .append($('<div class="info-line"><label>Product</label><p><select id="selectionresult2-'+i+'" name="selectionresult2-'+i+'" class="selectionresult2"></select><span id="result2-'+i+'" class="result2">&nbsp;</span></p></div>'))
                .append($('<a class="remove" href="#add-product" id="remove-product'+i+'"><img src="<?php echo base_url();?>img/remove-product.jpg" alt="" />Remove Product</a>'))
                .appendTo("#products");
    
            // START OF ADDITIONAL PRODUCT DROP DOWNS
            $("#selectionresult-" + i).hide();
            $("#selectionresult2-" + i).hide();
    
            $("#selection-" + i).change(function () {
    
                $(this).next(".selectionresult").hide();
                $(this).next(".selectionresult2").hide();
                $("#result-" + i).html('Retrieving ...');
                $.ajax({
                    type: "POST",
                    data: "data=" + $(this).val(),
                    url: "<?php echo base_url();?>dropdown.php",
                    success: function (msg) {
                        if (msg != '') {
                            $("#selectionresult-" + i).html(msg).show();
                            $("#result-" + i).html('');
                        }
                        else {
                            $("#result-" + i).html('<em>No item result</em>');
                        }
                    }
                });
    
            });
            $("#selectionresult-" + i).change(function () {
                $(this).next(".selectionresult2").hide();
                $("#result2-" + i).html('Retrieving ...');
                $.ajax({
                    type: "POST",
                    data: "data=" + $(this).val(),
                    url: "<?php echo base_url();?>dropdown.php",
                    success: function (msg) {
                        if (msg != '') {
                            $("#selectionresult2-" + i).html(msg).show();
                            $("#result2-" + i).html('');
                        }
                        else {
                            $("#result2-" + i).html('<em>No item result</em>');
                        }
                    }
                });
            });
    
         // End closure. Executes the closure function, passing in the
         //   current value of "i"
        })( i );
    });
    

    EDIT:

    To explain what is happening, in javascript, variables passed to (or created in) a function body are local to that function, and they persist.

    All I’m doing above is creating a function that accepts one parameter. Here I’ll change the name of the parameter to perhaps make it more clear:

    function( inner_i ) {
        // create your element with the new local variable "inner_i"
    }
    

    …but I’m also calling that function as soon as I create it:

    (function( inner_i ) {
        // create your element with the new local variable "inner_i"
    })( i )
    //  ^------- call the function, passing in the "i" from your loop.
    

    The syntax looks a little strange, but it is simply a way to call a function that you’ve just created.

    It would be the same as doing:

    function myNewFunction( inner_i ) {
        // creates your element with the new local variable "inner_i"
    }
    
    myNewFunction( i );  // Call the function we just created above, 
                         //   and pass the "i" from the loop into it
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Main method that creates a message loop called SysTrayApp: void Main()
At runtime I have a loop that creates a number of div s with
I have a loop that enters each non-empty text field into a database: foreach
I have a loop that can look like this: For Each article In artAll
On my jsp page I have a loop that loops elements in a collection,
I have the following PHP that creates some JSON from a MySQL query. This
I have some code that downloads lessons as JSON, parses them, and puts them
I have a loop that finds duplicate lines in a .ini file. I can
I have a loop that runs through a variety of websites and I'd like
I have a loop that runs for approx. 25 minutes i.e 1500 seconds. [100

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.