简体   繁体   中英

Get the value of select boxes from multiple forms

Basically, I'm repeating this form a couple of times, each with its own submit button. In this situation, I can't combine all of the select boxes from the forms into one form.

<form method="post" action="">
  <select name="hour" class="hour">
     // option tags
  </select>
  <select name="minutes" class="minutes">
    // option tags
  </select>
<input type="submit" name="submit" class="submit">
</form>

I'm using AJAX to process te values.

$(".submit").click(function() {
   var hour = $(".hour").val();
   var minutes = $(".minutes").val();
// AJAX code here
});

However, the variables 'hour' and 'minutes' will only hold the value of the select box from the first form. How can I let these variables have the correct value if the submit button is clicked on the second, of third form?

You can do this:

$(".submit").click(function () {
    var $form = $(this).closest('form');
    var hour = $form.find(".hour").val();
    var minutes = $form.find(".minutes").val();
    // AJAX code here
});

On click of the submit button it will go to the closest form and find the select list in it and get the respectives values accordingly. And then you can process the data.

Add a context, for example:

$(".submit").click(function() {
   var hour = $(".hour", $(this).parent()).val();
   var minutes = $(".minutes", $(this).parent()).val();
// AJAX code here
});

EDIT: This code is for your example only. If DOM structure differs changes may need.

Also you can use 'submit' event for form instead of 'click'. In this case you can use $(this) as context.

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