h4kl0rd
h4kl0rd

Reputation: 625

Dynamically generating form elements using jquery

There are multiple paragraphs in the page. Each paragraph must be followed by a div with two buttons Add and Edit. Clicking the Add button should create a textarea dynamically above it.

Related references that didn't work:

DEMO


enter image description here


HTML code:

<div id="notes"></div>

In my JavaScipt:

<script>
// get notes in json format from php array
var notes = <?php echo json_encode($notes); ?>;

// call the scan function to iterate through the notes
scan(notes);

function scan(obj)
{
    jQuery.each(obj, function(key, val) {
    if (val instanceof Object) {
    for ( var v in val ) {
        if (val[v]['type'] == 'Topic') {
           $("#notes").append('<h2 class="topic">'+val[v]['content']+'</h2>');
        }
        if (val[v]['type'] == 'Subtopic') {
           $("#notes").append('<h4 class="subtopic">'+val[v]['content']+'</h4>');
        }
        if (val[v]['type'] == 'Concept') {
           $("#notes").append('<h5 class="concept">'+val[v]['content']+'</h5>');
        }
        if (val[v]['type'] == 'Paragraph') {
           $("#notes").append('<p>'+val[v]['content']+'</p>');

           // append input for all paragraphs
           $('#notes').append('<div class="paragraphs">');
           $('#notes').append('<div id="block">');
           $('#notes').append('<p class="edit"></p>');
           $('#notes').append('<p>');
           $('#notes').append('<div id="para">');
           $('#notes').append('<p><textarea cols="40" rows="2" id="textarea"></textarea></p>');
           $('#notes').append('<button id="add" class="add success tiny">Add</button>');
           $('#notes').append('&nbsp;');
           $('#notes').append('<button id="startEdit" class="canEdit tiny">Edit</button>');
           $('#notes').append('</div>');
           $('#notes').append('</p>');
           $('#notes').append('</div>');
           $('#notes').append('</div>');

        }
        scan(val[v]);
        }   
     }
  });
};

// Add paragraph button

i = 1;
$('#textarea'+i).hide();

text = $('#textarea'+i).text();
var data = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';

$('.paragraphs').on('click', '#add'+i, function() {
  if ( $('#add'+i).text() == "Add" ) {

    ajaxRequest(data, 'editNotes', 'POST');  // POST request on editNotes

    $('#textarea'+i).show();
    $('#add'+i).text('Save');
    $('#textarea'+i).focus(function() {
        this.select();
    });
  }
  else if ( $('#add'+i).text() == "Save" ) {

    ajaxRequest(data, 'saveNotes', 'POST');  // POST request on saveNotes

    if ($('#textarea'+i).val() == ''){
      alert('Enter something...');
    } else {
      $('#add'+i).text("Add");
      $('#textarea'+i).hide();
      var overview = $('#textarea'+i).val();
      i++;
      console.log('after: i='+i);
      $('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
    }
  }

});
</script>

How do I add the form elements dynamically with incremental id and class names?

Any help is appreciated

Upvotes: 1

Views: 1025

Answers (1)

Jesse
Jesse

Reputation: 2848

unfortunately append does not work like it may seem, when you submit something like:

$('#element').append('<div>start here'):
$('#element').append('end here</div>'):

The very first call sent will close the div, it will actually create 2 separate elements. One way to help with this rather than having a large append as it can get kinda messy, is to create a variable and place all the elements into that variable and append it.

Example:

http://jsfiddle.net/h8V93/

var appends='<div class="paragraphs">'
            +'<div id="block">'
            +'<p class="edit"></p>'
            +'<p>'
            +'<div id="para">'
            +'<p><textarea cols="40" rows="2" id="textarea"></textarea></p>'
            +'<button id="add" class="add success tiny">Add</button>'
            +'&nbsp;'
            +'<button id="startEdit" class="canEdit tiny">Edit</button>'
            +'</div>'
            +'</p>'
            +'</div>'
            +'</div>';

            $('#notes').append(appends);

I hope this helps.

Update

Edit for further reading, the best way to actually do this is to create an html page as a separate file and include it like so:::

$.get("<urlhere>", function (data) {
    //Append, After, Before, Prepend data or whatever you want to do with it.
});

This is very convenient in GM or TM scripts where you keep the html file on your own server.

Hope this update helps future readers.

in recent versions of TM (tampermonkey), because of added cross domain origin policies, use GM_xmlhttpRequest -> http://wiki.greasespot.net/GM_xmlhttpRequest

Upvotes: 2

Related Questions