jQuery selecting the element itself

Asked

Viewed 94 times

0

Well I’m new in jQuery and I’m having a problem, as I do to select the element itself and not what is inside it, follows code:

$('#add_phone').bind('click', function(){
  var html = '';
  html += $('[camp=phone]').find('input');

  $('#add_phone_div').append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<div camp="phone">
  <input type="text" name="phone[]" data-inputmask='"mask": "(99) 9 9999-9999"' data-mask>
</div>
<div id="add_phone_div"></div>
<hr/>
<button id="add_phone">ADD CONTATO EXTRA</button>

What I intend to do is take the input HTML copy it and paste it into the id="add_phone_div div"

2 answers

2


$('#add_phone').bind('click', function() {
  const $input = $('[camp=phone]').find('input');
  const $clone = $input.clone();

  $('#add_phone_div').append($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<div camp="phone">
  <input type="text" name="phone[]" data-inputmask='"mask": "(99) 9 9999-9999"' data-mask>
</div>
<div id="add_phone_div"></div>
<hr/>
<button id="add_phone">ADD CONTATO EXTRA</button>

After obtaining the input, use the method clone() Jquery itself to literally generate a clone of the element itself, leaving only the cloned element to be inserted as a method parameter append.

  • 1

    Wow I didn’t know the clone() of jQuery, helped me a lot, thank you!

  • Jquery has several methods that save our code! Give nothing @Anorak!

0

You can do something like this:

$(function () {
    var clone = $("[name='phone[]']").html();
    $(document).on('click', '#add_phone', addPhone);

    function addPhone() {
        $('#add_phone_div').append(clone);
    }
}
  • If it doesn’t work, replace the .append for .html(clone)

  • Using $("[name='phone[]']"). html(); it does not select the element.

  • Well, I have a question, this your input will be only 1, or will you make others with the same name ? If it is only 1, Voce can assign an id to it and select it through the ID. With this, it copies the HTML of the same, or you can simply clone it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.