Home » Jquery » jquery – Delete a value of an array if exist on another array-Exceptionshub

jquery – Delete a value of an array if exist on another array-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a set of data on the table. Which are all owners.

  <table class="table">
  <tr>
    <td>
      <button id="John" onclick="deleteVal('John');" type="button"> Delete </button>
    </td>
    <td> <input type="text" name="owner[]" value="John"> John </td>
  </tr>
  <tr>
    <td><button id="Mike" onclick="deleteVal('Mike');" type="button"> Delete </button></td>
    <td> <input type="text" name="owner[]" value="Mike"> Mike </td>
  </tr>
  <tr>
    <td><button id="Sam" onclick="deleteVal('Sam');" type="button"> Delete </button></td>
    <td> <input type="text" name="owner[]" value="Sam"> Sam </td>
  </tr>
</table>

When the submit button is clicked all owners are stored to this final_owner field. This is what i’ve tried.

<button type="submit" id="submit">Submit</button>
FINAL OWNERS: <input type="text" id="final_owner">


 $('#submit').on('click', function() {
      var owner_value = [];
  var del_owners = document.getElementById('deleted_owners').value
      $('input[name="owner[]"]').each(function() {
          owner_value.push($(this).val());
      });
      $("#final_owner").val(owner_value);
});

Next is Each time I click Delete Button the owners name is stored to the deleted_owners input field. Which I already made.

My question is how can I remove from the array of final_owner field if the owner is already exist on the delete_owners input field.

<input type="text" id="deleted_owners">.
How to&Answer:

last line in $(‘#submit’).on(‘click’)… You can try this.

    var deleted_owners = $("#deleted_owners").val()
    var current_final_owner = $("#final_owner").val()

    var new_final_owner = current_final_owner.filter(item => !deleted_owners.inculdes(item))

    $("#final_owner").val(new_final_owner )

Edited

Answer:

try this with add delete buttons

Using Sets
when clicking on add,delete buttons

get our final_owner array from set

  Array.from(deleted_owner);

check live example :
https://codesandbox.io/s/crazy-goldstine-wf01q