删除具有相同名称属性的表单值

时间:2020-10-05 12:37:57

标签: javascript html jquery ajax

我有问题,我想删除一些名称并留下一些。但是当我尝试删除一个名字时,它会删除第一个名字,而您已经单击删除了最后一个名字。

所以重点是

我该如何删除或发送要删除的名称值,而不是删除第一个或全部。

因为它们都具有相同的名称“ info”,但值不同。 所以我想删除一些,而不是全部或仅保留在顶部

任何想法我该怎么做

$(document).ready(function() {
  $("#remove").click(function(event) {
    Execute();
  });

  function Execute() {
    $.ajax({
      type: 'POST',
      url: 'remove.php',
      data: {
        'info': $("input[name='info']").val()
      },
      success: function(response) {},
      error: function() {
        alert("error");
      }
    });
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
  <input type="text" name="info" value="John">
  <button type='button' id='remove'> delete</button>

  <input type="text" name="info" value="Jane">
  <button type='button' id='remove'> delete</button>

  <input type="text" name="info" value="jacobo">
  <button type='button' id='remove'> delete</button>
</form>

1 个答案:

答案 0 :(得分:0)

  1. 首先,对您的按钮使用class而不是id。该ID应该是唯一的。
  2. 第二,您可以获取单击按钮(目标)的先前输入。

$(document).ready(function() {
  $('.remove').click(function(event) {
    execute($(event.target).prev('input'));
  });

  function execute($input) {
    console.log(`Deleting: ${$input.val()}`);
    $.ajax({
      type: 'POST',
      url: 'remove.php',
      data: {
        'info': $input.val()
      },
      success: function(response) {},
      error: function() {
        alert("error");
      }
    });
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
  <input type="text" name="info" value="John">
  <button type="button" class="remove">Delete</button>

  <input type="text" name="info" value="Jane">
  <button type="button" class="remove">Delete</button>

  <input type="text" name="info" value="jacobo">
  <button type="button" class="remove">Delete</button>
</form>

相关问题