9 May 2016

Perintah JQuery untuk Menambah atau Menghapus Element


Metode-metode yang terkait dengan hal tersebut :

  • remove() : untuk menghilangkan elemen.
  • insertBefore : untuk menyisipkan elemen sebelum elemen yang disebutkan.
  • insertAfter : untuk menyisipkan elemen sebelum elemen yang disebutkan.
Contoh :
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Menambah dan Menghapus</title>
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script>
  $(document).ready(function() {
    //sembunyikan tombol hapus terlebih dahulu
$(".btn-hapus").hide();

//event pada tombol hapus
$(".btn-hapus").click(function(e){
var frmtarget = $(e.target).parent();
frmtarget.remove();
return false;
});

    //event pada tombol tambah
    var index = 2;
    $("#btn-tambah").click(function(){
    var komponen = $("<p id='data-"+ index + "'><label>Nama:</label>" +
    " <input type='text' name='nama[]'>" +
    "</p>");

    komponen.insertBefore("#btn-tambah");
    $(".btn-hapus:first")
    .clone(true)
    .appendTo("#data-" + index)
    .show();

    index = index + 1;
    return false;
    });

  });
  </script>
</head>
<body>
  <form>
  <p id="data-1">
  <label>Nama:</label>
  <input type="text" name="nama[]">
  <button type="button" class="btn-hapus">Hapus</button>
  </p>
  <button type="button" id="btn-tambah">Tambah</button>
  </form>

</body>
</html>
Semoga bermanfaat. :) Ingin mendownload filenya : Klik Disni.

Loading...

I am a fan of technology and i love coffee. I’m also interested in web programming and framework. below there are some accounts you can follow to contact me.

Comments

Thanks for comments.
EmoticonEmoticon