Why don't show specific id in action

Viewed 51

I am trying to delete by ID. But why don't show action=NaN in console.

Deleting..  form id="deletecategoryform" action="NaN" method="POST"

Here is my code

<script>
    function handleDelete(id){

       
        var form = document.getElementById('deletecategoryform')

        form.action = '/categories/' * id

        console.log('Deleting',form)

        $('#deleteModal').modal('show')
    }
   
</script>
1 Answers

Don't multiply '/categories/' * id
rather: concatenate Strings with +

form.action = '/categories/' + id;

or by using string Template Literals with backticks:

form.action = `/categories/${id}`;

There's more.
When using JS to tackle form submit you might want to prevent the browser of messing thigs up. In such case make sure to prevent the browser to submit the form by using Event.preventDefault() - or actually you don't need a form at all:

function removeItem(ev) {
  const $button = $(this);
  const id = $button.data("delete-id");
  
  $.ajax("/delete/"+ id)
    .done((res) => {
      console.log(res);
      // Remove button's LI parent:   
      $button.closest("li").remove();
    }).fail(err => {
      console.log(err);
    });
}

$(document).on("click", "[data-delete-id]", removeItem);
<ul>
  <li>
    Some item with ID 24 <button type="button" data-delete-id="24">DELETE</button>
  </li>
</ul>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related