Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
How can one use JS to add a draggable field?

What do I need to change in my code so that it generates draggable fields. This is what I have tried so far:

(function() {
  var counter = 0;
  var b = document.getElementById('b');
  var l = document.getElementById('l');
  var addInput = function() {
    counter++;
    var input = document.createElement("input");
    input.id = 'input-' + counter;
    input.className = 'd';
    l.appendChild(input);
  };
  b.addEventListener('click', function() {
    addInput();
  }.bind(this));
})();

$('.d').draggable({
  cancel: null
});
$('.d input').click(function() {
  $(this).focus();
});
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>

<script src="https://code.jquery.com/ui/1.8.18/jquery-ui.js"></script>

<button id="b" type="button">Add</button>
<br>

<label id="l" action="">
</label>

The code currently generates the fields but they are not draggable while being clicked.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're trying to set 'draggable' on the elements before they exist.

Try setting it (and your click handler) after you insert them into the DOM:

(function() {
  var counter = 0;
  var b = document.getElementById('b');
  var l = document.getElementById('l');
  var addInput = function() {
    counter++;
    var input = document.createElement("input");
    input.id = 'input-' + counter;
    input.className = 'd';
    l.appendChild(input);
    $(input).draggable({
      cancel: null
    })
    $(input).click(function() {
      $(this).focus();
    });
  };
  b.addEventListener('click', function() {
    addInput();
  }.bind(this));
})();
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>

<script src="https://code.jquery.com/ui/1.8.18/jquery-ui.js"></script>

<button id="b" type="button">Add</button>
<br>

<label id="l" action="">
</label>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda