【问题标题】:Submitting two different forms with an external Submit button not working properly使用外部提交按钮提交两种不同的表单无法正常工作
【发布时间】:2015-07-20 10:05:33
【问题描述】:

我正在创建一个添加到购物车程序,需要将产品及其属性(颜色、尺寸)添加到购物车中,为此我需要同时提交两个表单。我不确定我在哪里出错了我已经创建了脚本,但它只提交了使用 jquery 为submit() 选择的第一个表单,而不是其他表单。

下面是我的代码片段,这是 JSFIDDLE

$(document).ready(function (){
    $('#cart').click(function (e1) {
    var $form = $('#masterform');
    var $formcolor = $('#colorform');
    var $checkbox = $('.roomselect');
    var $checkboxcolor = $('.colorselect');
    if (!$checkbox.is(':checked'))
    {
        $('#tipdivcontent').css("display", "block");
        $("#tipdivcontent").delay(4000).hide(200);
        e.preventDefault();
    }
    else
    {
        if (!$checkboxcolor.is(':checked')) {
            $('#tipdivcontentcolor').css("display", "block");
            $("#tipdivcontentcolor").delay(4000).hide(200);
            e.preventDefault();
        } else {
            $form.submit();
            $formcolor.submit();
        }
    }
    });
});
#tipdivcontent
{
    border:1px solid black;
    margin-top:0px;
    background-color:white;
    height:50px;
    width:102px;
    display:none;
    position:relative;
    background-color:red;
    color:yellow;
    font-weight:bold;
}
#tipdivcontentcolor
{
    border:1px solid black;
    margin-top:0px;
    background-color:white;
    height:18px;
    width:292px;
    display:none;
    position:absolute;
    background-color:red;
    color:yellow;
    font-weight:bold;
}
<form action="" method="POST" id="masterform">
    <table border="1" cellspacing="0">
        <tr>
            <th colspan="4">Sizes</th>
        </tr>
        <tr>
            <td>
                <label for="2.2">2.2</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.2" name="size" value="twopointtwo">
            </td>
            <td>
                <label for="2.4">2.4</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.4" name="size" value="twopointfour">
            </td>
        </tr>
        <tr>
            <td>
                <label for="2.6">2.6</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.6" name="size" value="twopointsix">
            </td>
            <td>
                <label for="2.8">2.8</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.8" name="size" value="twopointeight">
            </td>
        </tr>
        <tr>
            <td colspan="3" align="center">
                <label for="2.10">2.10</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.10" name="size" value="twopointten">
            </td>
        </tr>
    </table>
</form>
<div id="tipdivcontent">Please Select Size.</div>
<input type="submit" value="To Cart" class="cartorcheckoutbutton" id="cart">
<form action="" method="POST" id="masterform">
    <table border="1" cellpadding="2">
        <tr>
            <th colspan="8">COLORS</th>
        </tr>
        <tr>
            <th title='White' style='background-color:white;' height='15' width='20'>
                <input type='radio' name='color' class="colorselect" value='white'>
            </th>
            <th title='Red' style='background-color:red;' height='15' width='20'>
                <input type='radio' name='color' class="colorselect" value='red'>
            </th>
            <th title='Green' style='background-color:green;' height='15' width='20'>
                <input type='radio' name='color' class="colorselect" value='green'>
            </th>
            <th title='Blue' style='background-color:blue;' height='15' width='20'>
                <input type='radio' name='color' class="colorselect" value='blue'>
            </th>
        </tr>
    </table>
</form>
<div id="tipdivcontentcolor">Please Select Color.</div>

【问题讨论】:

  • 为什么你不只使用一种形式??
  • @Vanojx1 我不能使用一种形式,因为我的购物车按钮、尺寸表和颜色表都位于不同的位置,并且它们也有不同的 css 自定义,所以我不能使用单一形式。
  • stackoverflow.com/questions/8563299/… 这个有一个解决方案,表单通过 ajax 请求提交。在第一次ajax调用成功后提交第二个表单。

标签: javascript php jquery html forms


【解决方案1】:

您可以尝试将辅助表单中的颜色输入分配给您的“主”表单。只需在任何输入上使用 &lt;input form='formID' ...&gt; 即可将该输入分配给另一个表单,而不管它在页面上的什么位置。

// When the 'master' form is submitted...
$("#masterForm").on("submit", function(e) {
  "use strict";
  // Stop the default action
  e.preventDefault();
  
  if ($("input[type='radio']:checked").length === 0) {
    alert("You must check at least one color option.");
    return false;
  }
  
  // *for logging*
  // write the contents of the submitted data
  $("p").html("submitted data: " + $(this).serialize());
  console.log("submitted data: " + $(this).serialize());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="masterForm">
  <input name="someField" type="text" value="test value">
</form>

<form id="anotherForm">
  <label>
    <input name="color" type="radio" value="blue" form="masterForm">Blue
  </label>
  <label>
    <input name="color" type="radio" value="red" form="masterForm">Red
  </label>
</form>

<!-- Submit button outside of the form -->
  <button type="submit" form="masterForm">Submit</button>

<p></p>

如果上述选项(以及附加的 sn-p)对您不起作用,请尝试在您的 formData 中附加相关字​​段。像这样的东西(未经测试):

// When the 'master' form is submitted...
  $("#masterForm").on("submit", function(e) {
  "use strict";
  // Stop the default action
  e.preventDefault();

  var submissionData = $(this).serialize();
  submissionData += "&color=" + $("#slaveForm").find("input[name='color']:checked").val()

  // do stuff ...
});

【讨论】:

  • 只有当两个表单都输入了值大小和颜色应该至少有一个勾号用于提交表单并且我的提交按钮不在表单内所以需要从外部提交时,我才需要提交表单形式。
  • 参见上面的编辑代码。通过从表单中移动提交按钮并应用form='...' 标签,您可以获得相同的结果。关于颜色要求,只需检查无线电输入并在未检查任何内容时提醒用户即可。
【解决方案2】:

表单是通过 POST 请求(或 GET)发送的一组数据。你所要求的毫无意义。如果可能,那么您仍然不应该这样做。无论 HTML 和 CSS 问题使您拆分表单,我建议您将其作为您的实际问题放在这里。

【讨论】:

    【解决方案3】:

    提交表单,除非它具有指向框架或其他窗口的目标属性,否则将导致生成新页面的 HTTP 请求。

    同时提交两个表单就像同时访问两个链接。做不到。

    您需要:

    • 重构您的代码,使其使用单一形式。这几乎肯定是最有意义的。
    • 向页面添加一对框架并将每个表单提交给不同的表单。
    • 使用 JavaScript 为第一个表单收集数据,使用 Ajax 将其发送到服务器,然后(在收到响应后)提交第二个表单。

    【讨论】:

      【解决方案4】:

      如果您想将多个表单作为一个表单发送,我可以建议使用 formData 对象(文档https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

      var formData = new FormData();
      
      formData.append("size", $('input[name=size]:checked').val());
      
      formData.append("color", $('input[name=color]:checked').val());
      
      var request = new XMLHttpRequest();  
      request.open("POST", "yourformtarget");
      request.send(formData);
      

      【讨论】:

        【解决方案5】:

        使用javascript的一种可能的解决方案:您可以添加一个属性来定位所有字段,并通过ajax发送表单:

        <div id='masterform'>
            <input name='field_1' data-field-of='form1'>
            ...
        </div>
        ...
        <div id='colorform'>
            <input name='field_23' data-field-of='form1'>
             ...
        </div>
        

        javascript中的代码可以是这样的:

        $(document).ready(function (){      
        
            $('#cart').click(function (e1) {
                var data = $('[data-field-of=form1]').serialize();
                $.ajax({
                    url: "post/url",
                    data: data,
                    type: "POST",
                    success: function(response){ /* handle success */ },
                    error: function(){ /* handle error */ }
                });
            });
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-31
          • 2018-01-29
          • 2014-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-11
          • 1970-01-01
          相关资源
          最近更新 更多