簡體   English   中英

在包含提交按鈕的表單標簽之外發布輸入字段的值

[英]Posting values of input fields outside form tag containing submit button

我有 3 個不在表單標簽內的輸入字段。 我無法將它們添加到表單中,因為三個輸入字段位於同一頁面上的不同位置。

當我按下提交按鈕時,我也想在表單標簽之外發布輸入值。 我怎樣才能做到這一點?

<input input type="text" id="elecr"  value="2" name="electricity"></input>
<input input type="text" id="3wheel"  value="3" name="threewheel"></input>
<input input type="text" id="4wheel"  value="2" name="fourwheel"></input>

<form action="/savedata" method="post">
2Wheeler: <input type="text" id="2wheeler"  value="0" name="twowheeler"/><br><br>
<input type="submit" />
</form>
  1. 編寫 javascript 處理提交事件
  2. 在提交事件 append 您的輸入與表單數據
  3. 提交

供參考,請參閱在提交前添加 POST 參數

$( 'form' ).submit(function ( e ) {
    var data;

    data = new FormData();
    data.append( 'electricity', $('#elecr').val());
    data.append( 'threewheel', $('#3wheel').val());
    data.append( 'fourwheel', $('#4wheel').val());

    $.ajax({
        url: 'savedata.php',
        data: data,
        processData: false,
        type: 'POST',
        success: function ( data ) {
            alert( data );
        }
    });

    e.preventDefault();
});

只需通過 jquery 存儲所有輸入字段的值,然后單擊提交按鈕通過 ajax 提交您的表單。

$('form').submit(function(event) {

    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)
    var formData = {
        'electricity'  : $('input[name=electricity]').val(),
        'threewheel'   : $('input[name=threewheel]').val(),
        'fourwheel'    : $('input[name=fourwheel]').val(),
        'twowheeler'   : $('input[name=twowheeler]').val(),
    };

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'savedata.php', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
        encode      : true
    })

您可以在 jquery 中記錄並進行錯誤處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM