首页 > 解决方案 > 删除具有相同名称属性的表单值

问题描述

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

所以重点是

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

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

知道我该怎么做

$(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>

标签: javascripthtmljqueryajax

解决方案


  1. 首先,为您的按钮使用 aclass而不是 an 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>


推荐阅读