0

I want to create dynamic objects using jquery..

I know I can use this method

$('#container').append('<div class="relation"><input type="text" name="relation"></div>');

but in this way, the html string will be a very long to achieve.

i have this html

<div class="box-content">
<fieldset>
    <legend><h6>Select Conditions</h6></legend>
        <div class="control-group" id="relation_container">
        <div class="relation-parent_0">
            <div class="relation-left" id="relation_0">
            <select name="key[]" id="key_0" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <select name="condition[]" id="condition_0" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <input type="text" name="constraint[]" id="constraint_0" class="relation-input" data-provide="typeahead" data-items="2" style="" />
            </div>
            <div class="relation-reight">
            <button type="reset" class="btn">X</button>
            </div>
        </div>
        </div>                            

</fieldset>
<button type="button" class="btn btn-primary" onclick="add_relation();">Add More</button>
</div>

Now I want this section to be generated dynamically

<div class="relation-parent_0">
            <div class="relation-left" id="relation_0">
            <select name="key[]" id="key_0" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <select name="condition[]" id="condition_0" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <input type="text" name="constraint[]" id="constraint_0" class="relation-input" data-provide="typeahead" data-items="2" style="" />
            </div>
            <div class="relation-reight">
            <button type="reset" class="btn">X</button>
            </div>
        </div>

EDIT:

I modified the answer by bart s

and rewrite the script like this,

but it seems to have some error

var i = 0;
    function add_relation()
    {
        i = i + 1;

        var memtag = $('<div />', {
                                    'class' : 'relation-parent_' + i,
                                     html    : $('<div />', {
                                                               'class' : 'relation-left',
                                                               'id'    : 'relation_' + i,
                                                                html    : $('<select />', 
                                                                              {
                                                                             'class'  : 'relation-select',
                                                                             'id'     : 'key_' + i,
                                                                             'name'   : 'key[]'
                                                                              })
                                                            }
                                                ),
                                                $('<div />', {
                                                               'class' : 'relation-right',
                                                                html    : $('<button />', 
                                                                              {
                                                                             'class'  : 'btn',
                                                                             'name'   : 'btn[]'
                                                                              })
                                                            }
                                                )
                                    });

        $("#relation_container").append(memtag);
    }

Finaly I Got The Answer

var i = 0;
    function add_relation()
    {
        i = i + 1;
        var left = $('<div />', {'class' : 'relation-left','id'    : 'relation_' + i}).append($('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'key_' + i,
                                 'name'   : 'key[]'
                             })).append($('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'condition_' + i,
                                 'name'   : 'key[]'
                             })).append($('<input />', {
                                 'class'  : 'relation-input',
                                 'id'     : 'constraint_' + i,
                                 'type' : 'text',
                                 'name'   : 'constraint[]',
                                 'data-provide' : 'typeahead',
                                 'data-items' : '2'

                             }));
        var right = $('<div />', {'class' : 'relation-right',html : $('<buton />', 
                                                                            {
                                                                            'class' : 'btn',
                                                                            'name' : 'btn[]',
                                                                            'value': 'X'})
                                                                    });


        var parent = $('<div />', {'class' : 'relation-parent_' + i}).append(left).append(right);
    $("#relation_container").append(parent);
    }

Here's the final script:

<style>
    .relation-left
    {
        float:left; 
        width: 80%;
    }
    .relation-right
    {
        float:left; 
        margin: 0 0 0 30px;
    }
    .relation-select
    {
       width: 120px !important;
       float:left;
       margin: 0 0 0 2px
    }
    .relation-input
    {
       width: 120px !important;
       margin: 0 0 0 12px
       float:left;
    }
    </style>

    <script type="text/javascript">
    function condition_toggle(condition)
    {
        if(condition==1)
            $("#condition_div").fadeOut('slow');
        else
            $("#condition_div").fadeIn('slow');
    }

    var i = 0;
    function add_relation()
    {
        i = i + 1;
        var left = $('<div />', {'class' : 'relation-left','id'    : 'relation_' + i}).append($('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'key_' + i,
                                 'name'   : 'key[]'
                             })).append($('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'condition_' + i,
                                 'name'   : 'key[]'
                             })).append($('<input />', {
                                 'class'  : 'relation-input',
                                 'id'     : 'constraint_' + i,
                                 'type' : 'text',
                                 'name'   : 'constraint[]',
                                 'data-provide' : 'typeahead',
                                 'data-items' : '2'

                             }));
        var right = $('<div />', {'class' : 'relation-right',html : $('<buton />', 
                                                                            {
                                                                            'class' : 'btn',
                                                                            'name' : 'btn[]',
                                                                            'value': 'X'})
                                                                    });


        var parent = $('<div />', {'class' : 'relation-parent_' + i}).append(left).append(right);
    $("#relation_container").append(parent);
    }
    </script>   
            <div class="row-fluid sortable">
                <div class="box span12">
                    <div class="box-header well" data-original-title>
                        <h2><i class="icon-edit"></i> Add collection</h2>
                        <div class="box-icon">
                            <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a>
                            <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a>
                            <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a>
                        </div>
                    </div>
                    <div class="box-content">
                        <form class="form-horizontal" action="<?php echo base_url() ?>admin.php/collection/add_collection" method="post" enctype="multipart/form-data">
                          <fieldset>
                            <legend><?php if(isset($msg)) echo $msg;?></legend>
                            <div class="control-group">
                              <label class="control-label" for="typeahead">collection Name</label>
                              <div class="controls">
                                <input type="text" name="title" class="span6 typeahead" id="title"  data-provide="typeahead" data-items="4" >
                              </div>
                            </div>
                            <div class="control-group">
                              <label class="control-label" for="fileInput">File input</label>
                              <div class="controls">
                                <input class="input-file uniform_on" name="img" id="img" type="file">
                              </div>
                            </div>          
                            <!--<div class="control-group" >
                              <label class="control-label" for="textarea2">Description</label>
                              <div class="controls" style="overflow-x: auto;">
                                <textarea class="cleditor" name="cont" id="cont" rows="3"></textarea>
                              </div>
                            </div>-->
                            <div class="control-group">
                                <label class="control-label">Conditions</label>
                                <div class="controls">
                                  <label class="radio">
                                    <input type="radio" name="gender" id="optionsRadios1" value="1"
                                    onclick="condition_toggle(this.value);">
                                    Manual(Product Added Manualy)
                                  </label>
                                  <div style="clear:both"></div>
                                  <label class="radio">
                                    <input type="radio" name="gender" id="optionsRadios2" value="2"
                                    onclick="condition_toggle(this.value);">
                                    Automatic(products addition automated)
                                  </label>
                                </div>
                                <div class="controls" id="condition_div" style="display:none; border: 1px solid #cfcfcf; margin-top: 5px;">
                                  <div class="box-content">
                                          <fieldset>
                                            <legend><h6>Select Conditions</h6></legend>
                                            <div class="control-group" id="relation_container">
                                                <div id="relation-parent_0">
                                                    <div class="relation-left">
                                                    <select name="key[]" id="key_0" class="relation-select">
                                                        <option value="">Select Brand</option>
                                                        <option value="">Select Brand</option>
                                                    </select>
                                                    <select name="condition[]" id="condition_0" class="relation-select">
                                                        <option value="">Select Brand</option>
                                                        <option value="">Select Brand</option>
                                                    </select>
                                                    <input type="text" name="constraint[]" id="constraint_0" class="relation-input" 
                                                    data-provide="typeahead" data-items="2" style="" />
                                                    </div>
                                                    <div class="relation-right">
                                                    <button type="reset" class="btn">X</button>
                                                    </div>
                                                </div>
                                            </div>                            

                                          </fieldset>
                                          <button type="button" class="btn btn-primary" onclick="add_relation();">Add More</button>
                                    </div>
                                </div>
                            </div>  
                            <div class="form-actions">
                              <button type="submit" class="btn btn-primary">Save changes</button>
                              <button type="reset" class="btn">Cancel</button>
                            </div>
                          </fieldset>
                        </form>   

                    </div>

                </div><!--/span-->
                                <div>
                                                          <a href="<?php echo base_url();?>admin.php/collection">
                                                             <button class="btn btn-large btn-success">View collection Listings</button>
                                                          </a>

                                        </div>
            </div><!--/row-->



                    <!-- content ends -->
            </div><!--/#content.span10-->
                </div><!--/fluid-row-->

        <hr>
6
  • Have a look at this github.com/codepb/jquery-template Commented Jul 30, 2014 at 11:46
  • If repetative data is there use jquery template Commented Jul 30, 2014 at 11:55
  • You mean, you have to append multiple sections as specified above ?. If so I suggest to create template for the appending section using jQuery template/handlebar.js/mustache.js. It is more faster binding. Commented Jul 30, 2014 at 11:59
  • i also need to generate id for the divs.... all the example I saw, they are not generating div. Commented Jul 30, 2014 at 12:01
  • you can create tags with jQuery in memory like described here http://stackoverflow.com/a/13952809/474535 You can use dynamic Id's etc. Commented Jul 30, 2014 at 12:11

2 Answers 2

1

You can build in memory html tags with jQuery like this (which is partial of what you would need).

var i = 0;

var memtag = $('<div />', {
     'class' : 'relation-parent_' + i,
     html    : $('<div />', {
                   'class' : 'relation-left',
                   'id'    : 'relation_' + i,
                   html    : $('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'key_' + i,
                                 'name'   : 'key[]'
                             })
                )}
)};

// use variable memtag to insert html into the DOM

The nesting however makes it very unreadable. If this is what you are looking for, you can assign the tags to variables and assmble the whole html structure later. This is a lot of work, and it is not very maintainable.

You could also get things doen with e.g. Angular JS or other frameworks

Update after question was updated

See this fiddle The internal div's have been taken out and assigned to variables. Instead of comma separating multiple objects in the original html, you must add them as they are not strings but objects.

    i = i + 1;

    var html1 = $('<div />', {
                   'class' : 'relation-left',
                   'id'    : 'relation_' + i,
                    html    : $('<select />', 
                                  {
                                 'class'  : 'relation-select',
                                 'id'     : 'key_' + i,
                                 'name'   : 'key[]'
                                  })
                });
    var html2 = $('<div />', {
                           'class' : 'relation-right',
                            html    : $('<button />', 
                                          {
                                         'class'  : 'btn',
                                         'name'   : 'btn[]'
                            })
                });

    var memtag = $('<div />', {
        'class' : 'relation-parent_' + i,
         html    : html1.add(html2)
    });

    $("#relation_container").append(memtag);
Sign up to request clarification or add additional context in comments.

Comments

0

if you are using template engines, you can easily pass new Id as JSON to your templates. Check the code below.

Note: Add jquery template library script reference and jquery library For Ref : https://github.com/BorisMoore/jquery-tmpl

<script id="SampleTemplate" type="text/x-jquery-tmpl">
    <div class="relation-parent_${Id}">
            <div class="relation-left" id="relation_${Id}">
            <select name="key[${Id}]" id="key_${Id}" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <select name="condition[${Id}]" id="condition_${Id}" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <input type="text" name="constraint[${Id}]" id="constraint_${Id}" class="relation-input" data-provide="typeahead" data-items="2" style="" />
            </div>
            <div class="relation-reight">
            <button type="reset" class="btn">X</button>
            </div>
        </div>

</script>

and for compile the template call like below

var NewId={"Id":1};
$("#SampleTemplate").tmpl(NewId).appendTo("#relation_container");

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.