简体   繁体   中英

Accessing form elements under submit function without defining the form name

I do have a form and submitting it via a submit function. Bur for submission variable I'm not utilizing document id but classes.

 $(".modalform").submit(function(event) { /* stop form from submitting normally */ event.preventDefault(); // get all the inputs into an array. var $inputs = $('this:input'); console.log($inputs.val()) /* get the action attribute from the <form action=""> element */ var $form = $(this), url = $form.attr('action'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Could be seen that this submit function is not based on ids but classes. I do have multiple forms with different ids and same class names and when I submit each of them, I want to have their elements and values in an array. There is this answer but it takes form ids an argument. I want an approach that could get the submitted forms id by any means and serialize values according to that (the mentioned answer can be used after obtaining form id).

You get the values like this

$(".modalform").submit(function(event) {
  /* stop form from submitting normally */
  event.preventDefault();
  // get all the inputs into an array.
  var $inputs = $(this).find(':input');
  const vals = $inputs.map(function() { return this.value }).get()
  console.log(vals)
  /* get the action attribute from the <form action=""> element */
  var $form = $(this),
    url = $form.attr('action');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM