Adding a dynamically element with jQuery

12

I have set up the following structure in HTML:

<form name="criaModelo" method='post' action=''>
  <label for="name">
    <strong>Nome:</strong>
    <input name="nomeModelo" type="text">
  </label>

  <h2>Associando Instruções</h2>

  <img src="images/4.png" class="btnNewInst btnHover" title="Inserir nova instrução" />

  <label for="criaAssoc" class="instAssoc">
    <strong>ID:</strong>
    <input type="text">
    <strong>Ordem:</strong>
    <input type="text">

    <span>
      <strong class="instTxt">Instrução:</strong>
      <textarea disabled="disabled"></textarea>
    </span>
  </label>

  <h2>Associando Tempo</h2>

  <img src="images/4.png" class="btnNewTime btnHover" title="Inserir nova instrução" />

  <label class="time">
    <strong>ID:</strong>
    <input type="text" style="width:25px;">
    <div>
      <strong>Total:</strong>
      <span>12:12:12</span>
      <strong class="margem">Tipo:</strong>
      <span>visível</span>
      <strong class="margem">Momento:</strong>
      <span>12:12:12</span>
      <strong class="margem">Ordem:</strong>
      <span>Crescente</span>
    </div>
  </label>

  <input type="submit" name="btnCriaModelo" class="newbtn" value="Criar"> 
</form>

Which has the following result:

I wanted to click this button to add to the form after the last current element this HTML to create a new label as above.

<label for="criaAssoc" class="instAssoc">
  <strong>ID:</strong>
  <input type="text">
  <strong>Ordem:</strong>
  <input type="text">

  <span>
    <strong class="instTxt">Instrução:</strong>
    <textarea disabled="disabled"></textarea>
  </span>
</label>
    
asked by anonymous 29.01.2014 / 04:52

2 answers

11

I suggest you keep this label as a template (ie leave it in its initial state, empty and invisible), and clone others from it:

<label id="meuTemplate" for="criaAssoc" class="instAssoc" style="display:none">
    ...
</label>
var clone = $("#meuTemplate").clone();
clone.prop("id", novoId); // É necessário mudar o id depois que se clona

Then you can select the latest label and insert after it :

$(".instAssoc:last").after(clone);
clone.show();

Example in jsFiddle .

Update: to access a particular element within of this item you just created, see the .find (it searches all descendants). And if you want an element to exclude itself, use the .remove (or .detach , if you intend to reinsert this element into the DOM later, eg drag-and-drop / drag-and-drop ). Example:

clone.find(".botaoExcluir").click(function() {
    clone.remove();
});

Updated example .

    
29.01.2014 / 05:58
5

Now, I know the question is what it would be like using jQuery, but I'd rather answer it as it should be done , since what you want to do will be replicated several times in your project screens with similar or even more complex behaviors) and an MVVM library falls like a glove. As an example, I cite my favorite knockoutjs .

Libraries of MVVM abstract task of the programmer in having to synchronize the user interface with the data and knockoutjs does this of a very semantic way, you can basically create extremely complex behaviors without any coupling between the data you want to work the view.

As an example, I made this little plunk . Click on the "Code" tab and then on script.js and then on index.html and see how simple it is to work with it.

----- update

As was suggested, all the code used in the solution is below, which, as you can see, is very simple and easy to understand.

Javascript

var 
    minhaView = {

        //lista de registros
        registros: ko.observableArray([]),
        id: ko.observable(""),
        ordem: ko.observable(""),

        incluirNovo: function(el) {

          //incluo na lista
          this.registros.push({id: this.id(),ordem: this.ordem()});

          //limpo textboxes
          this.id(""), this.ordem("");
        }
      }

ko.applyBindings(minhaView);

HTML

<label for="txtId">ID</label>
<input type="text" id="txtId" data-bind="value: id" />
<label for="txtOrdem">Ordem:</label>
<input type="text" id="txtOrdem" data-bind="value: ordem"/>
<button data-bind="click: incluirNovo">+</button>
<h2>Relação de itens</h2>
<ul data-bind="foreach: registros(), visible: registros().length > 0">
    <li>ID: <span data-bind="text: id"></span> - Ordem:<span data-bind="text: ordem"></span>
    </li>
</ul>
<span data-bind="visible: registros().length===0">Ainda não existem itens registrados.</span>
    
29.01.2014 / 07:10