4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javascript JQuery

Last updated at Posted at 2019-10-23
jquery
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
</body>
  <input type="text" id="text1">
  <button id="register">追加</button>
  <div id='id1'></div>

<script>
  let items = [];

  function createTable() {
    if (items.length <= 0) {
      $('#id1').html('');
      return;
    }
    let table = '<table border="1">';
    for (const i in items) {
      table += `<tr><td>${items[i]}</td><td><input type='button' onclick='update(${i})' value='編集'></td><td><input type='button' onclick='del(${i})' value='削除'></td></tr>`;
    }
    table += '</table>';
    $('#id1').html(table);
  }

  $('#register').click(() => {
    items.push($('#text1').val());
    createTable();
  });

  function del(i) {
    items.splice(i, 1);
    createTable();
  }

  function update(i) {
    items[i] = $('#text1').val();
    createTable();
  }
</script>
</html>
jquery
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
</body>
  <input type="text" id="text1">
  <button id="register">追加</button>
  <button id="search">検索</button>
  <table id='tbl'></table>

<script>
  let items = [];

  function createTable(items) {
    let tbl = '';
    for (const i in items) {
      tbl += `<tr><td>${items[i]}</td><td><button class="item" id="update-${i}">編集</button></td><td><button class="item" id="delete-${i}">削除</button></td></tr>`;
    }
    $('#tbl').removeAttr('border');
    if (tbl) { 
      $('#tbl').attr('border','1');
    }
    $('#tbl').html(tbl);
  }

  $('#register').click(() => {
    items.push($('#text1').val());
    createTable(items);
  });

  $('#search').click(() => {
    const val = $('#text1').val();
    const items2 = items.filter(i => i.indexOf(val) >= 0);
    items = items2;
    createTable(items);
  });

  $(document).on('click', '.item', function() {
    const tmp = $(this).attr('id').split('-');
    const type = tmp[0];
    const id = tmp[1];
    if (type === 'update') {
      items[id] = $('#text1').val();
    } else if (type === 'delete') {
      items.splice(id, 1);
    }
    createTable(items);
  })
</script>
</html>


4
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?