Home > Software engineering >  javascript : Identify the form in the loop after submission?
javascript : Identify the form in the loop after submission?

Time:06-20

I have a loop that creates 4 forms in the view And I put a button for each form to submit the form? What solution would you suggest to find out which form was submitted? Html :

@foreach (var item in 4){
<form id="Form_ImgGallery" method="post">
    <div >                       
        <input type="file" >
        <div >
            <input  type="submit"  value="upload">
        </div>
    </div>
</form>

}

CodePudding user response:

Maybe you should give each of the forms a different id. and then via id you can find out which form was submitted. here is a sample for getting idea.

const form = document.querySelector("#Form_ImgGallery");
form.addEventListener("submit", function (e) {
    e.preventDefault();
    console.log(e.target.attributes.id.value);  //Form_ImgGallery
});

CodePudding user response:

The issue you have is that your loop is creating multiple elements with the same id, which is invalid. Within a single page, there can be no duplication of id. If you want to group elements, then use a class. This is what I've done in the example below.

From there you can use the this keyword in the event handler to refer to the specific form element which raised the submit event, and get information from it, or one of the form fields it contains.

$('.Form_ImgGallery').on('submit', e => {
  e.preventDefault(); // stop the form submitting in this example
  let $form = $(e.target);
  let file = $form.find('input[type="file"]').val();
  console.log(file);
});

/* plain JS version:
document.querySelectorAll('.Form_ImgGallery').forEach(form => {
  form.addEventListener('submit', e => {
    e.preventDefault(); // stop the form submitting in this example
    let file = e.target.querySelector('input[type="file"]').value;
    console.log(file);
  });
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form  method="post">
  <div >
    <input type="file" >
    <div >
      <button type="submit" >upload</button>
    </div>
  </div>
</form>

<form  method="post">
  <div >
    <input type="file" >
    <div >
      <button type="submit" >upload</button>
    </div>
  </div>
</form>

<form  method="post">
  <div >
    <input type="file" >
    <div >
      <button type="submit" >upload</button>
    </div>
  </div>
</form>

<form  method="post">
  <div >
    <input type="file" >
    <div >
      <button type="submit" >upload</button>
    </div>
  </div>
</form>

  • Related