简体   繁体   English

使用 JQuery 收集表单数据并删除或隐藏表单字段

[英]Collecting form data and removing or hiding a form field using JQuery

I'm currently working on a problem that basically involves processing all data in a form, saving it, and replacing the entire form with a text link.我目前正在解决一个问题,该问题基本上涉及处理表单中的所有数据,保存它,并用文本链接替换整个表单。 My primary goal is to convert a form, with some data using the POST method, and a submit button, into a standard text link that can then take the saved/serialized data and POST it to the server as if it were the original form;我的主要目标是使用 POST 方法将包含一些数据和提交按钮的表单转换为标准文本链接,然后该链接可以获取保存/序列化的数据并将其 POST 到服务器,就好像它是原始表单一样; and when JS is disabled, the standard form and submit button is presented, ie a graceful degradation.当JS被禁用时,标准的表单和提交按钮被呈现,即优雅的降级。 I'm currently using jQuery, I know it's possible to process form data by serializing it, but I'm not sure how to go about removing or hiding (whichever one is possible) a form completely so it doesn't interfere with the layout of surrounding HTML element.我目前正在使用 jQuery,我知道可以通过序列化来处理表单数据,但我不确定如何完全删除或隐藏(无论哪种方式)表单,这样它就不会干扰布局周围的 HTML 元素。

In summary:总之:

-Is it possible to remove or hide an entire form field with jQuery? - 是否可以使用 jQuery 删除或隐藏整个表单字段?

-When jQuery serializes form data, where is it saved to? - jQuery序列化表单数据时,保存到哪里?

-Can that saved data be referenced by a text link (ie <a href="mySavedData">Submit</a>" ) somehow and POSTed as if it were a standard form? - 可以通过文本链接(即<a href="mySavedData">Submit</a>" )以某种方式引用已保存的数据并像标准表单一样发布?

Thank you.谢谢你。

UPDATE : Ok, I implemented Franz's code in a separate JS file I call from my test.html page.更新:好的,我在我从 test.html 页面调用的单独 JS 文件中实现了 Franz 的代码。 The content of the JS file is as follows: JS文件内容如下:

$(document).ready(function() {
  //Store form data before removing
    var tempStorage = $('.postLink').serialize();

  // Remove form:
    $('.postLink').remove();

    //Assign onClick event to anchor tag
    $('.submit').click(function(){
        $.ajax({
            //aspx page
            url:"doSomethingImportant/10",

            //Using POST method
            type: "POST",

            //The data object
            data: tempStorage,

            //No caching
            cache: false,

            //Alert on success
            success: function(html) {
            alert('great');
            }
        });
    });
});

The only difference here is I'm using the class attribute as an identifier for the forms I want removed as opposed to id.这里唯一的区别是我使用 class 属性作为我想要删除的表单的标识符,而不是 id。 Again, this is what I'm tasked with, not by choice.同样,这是我的任务,而不是选择。 For some reason, however, it doesn't make it to the alert message, ie it doesn't work.然而,出于某种原因,它没有进入警报消息,即它不起作用。 Below is the snippet of html I'm having the script act on:下面是我让脚本执行的 html 片段:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<style type="text/css">
h1.intro {color:blue;}
p.important {color:green;}
h2.outro {color:DarkGreen;}
</style>

<script type="text/javascript" src="jQuery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="Form2Link.js"></script>

<title>Form Remover demo</title>
</head>

<body>
<h1 class="intro">Hello World!!</h1>

<p>How's it going??</p>

<a href="">my First Link</a>
<form id = "myForm" name="myForm" action="doSomethingImportant/10" class="postLink" method="post">
<input type="submit" id="submitThis" name="submitThis" value="clickThisLink"></input>
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
</form>
<a class="submit" href="">Submit Link</a>
<a href="">my Second Link</a>
<a href="">my Third Link</a>

<br>
<br>

<form action="doSomethingImportant/10" method="post">
<input type="submit" id="submitThis" value="clickThisLink"></input>
<input type="hidden" value="12345" name="antiCSRF"></input>
</form>

<form action="doSomethingImportant/11" method="post">
<input type="submit" value="clickThisLink"></input>
<input type="hidden" value="12345" name="antiCSRF"></input>
</form>

<h2 class="outro">That's nice, gotta go.</h2>
</body>

</html>

UPDATE 11/10/09: Ok, I've found an alternate way of going about this problem by hiding the form and adding an anchor tag immediately after the form. 2009 年 11 月 10 日更新:好的,我找到了另一种解决此问题的方法,即隐藏表单并在表单后立即添加一个锚标记。 I then attach a click operation to the anchor that acts on the submit button in the hidden form.然后,我将单击操作附加到作用于隐藏表单中的提交按钮的锚点。 My problem now is that this only works with one form defined in the DOM, I want to come up with a generalization of this function so that it works with several forms.我现在的问题是这只适用于 DOM 中定义的一种形式,我想提出这个函数的概括,以便它适用于多种形式。 How can I traverse each form and replace it with its own unique link?如何遍历每个表单并用其自己的唯一链接替换它?

Code for my current script:我当前脚本的代码:

/**
 * Hide forms on page load.
 * Call submit button within a form from a link
 */
$(document).ready(function() {
    //Hide form:
    $('.postLink').hide();

    //Append a anchor tag after each form that is replaced
    $('.postLink').after("<a class=\"submitLink\" href=\"#\">Submit Link</a>");


    //Submit button in hidden form
    $('.submitLink').click(function(){
        $('#myForm').find('input#submitThis').click();
        return false;
    });
});

Part 1 is easy:第 1 部分很简单:

$('#yourform').hide();

EDIT: ( to the best of my understanding - using ScottE's step-by-step idea)编辑:(据我所知- 使用 ScottE 的循序渐进的想法)

Part 2:第2部分:

Save the form in a local variable:将表单保存在局部变量中:

var tempStorage = $('#yourform').serialize();

Part 3:第 3 部分:

Assign a function to the onClick event of your link that sends the data via an AJAX request:为通过 AJAX 请求发送数据的链接的 onClick 事件分配一个函数:

$('#yourbutton').click( function() {
    $.ajax({  
        // Your PHP processing script goes here  
        url: "yourfile.php",

        // You wanted to use POST, right?
        type: "POST",

        // The data object (I hope, it's accessible here)
        data: tempStorage,

        // We don't need caching
        cache: false,

        // A function that gets executed on success
        // Note that you have the response of the script in the html variable
        success: function(html) {
            alert('great');
        }
    });
});

If I understand what you're looking for, you could do the following:如果我了解您要查找的内容,您可以执行以下操作:

  1. handle the submit event of the form.处理表单的提交事件。
  2. store the form data in a local variable in js - look to http://docs.jquery.com/Ajax/serialize将表单数据存储在 js 的局部变量中 - 查看http://docs.jquery.com/Ajax/serialize
  3. hide the form隐藏表格
  4. show the link that will submit the form (again), and handle it's click event, initiating an ajax call where you pass in the local variable created in step 2.显示将提交表单的链接(再次),并处理它的点击事件,启动一个 ajax 调用,您传入在步骤 2 中创建的局部变量。

This seems like an odd request...这似乎是一个奇怪的要求......

Ok all, I went the route of hiding all my forms and appending anchor tags following each form based with class="postLink" , I added a conditional statement that adds a unique ID if a form doesn't already have one, the script then adds an anchor tag with the unique ID and the value of the submit button to the end of the hidden form.好吧,我选择了隐藏所有表单并在每个基于class="postLink"表单后面附加锚标记的路线,我添加了一个条件语句,如果表单还没有一个,则添加一个唯一的 ID,然后脚本在隐藏表单的末尾添加一个带有唯一 ID 和提交按钮值的锚标记。 A separate click function the processes the submit button in the hidden form that is tied to an anchor tag by the unique ID.一个单独的点击函数处理隐藏表单中的提交按钮,该表单通过唯一 ID 绑定到一个锚标签。 Code follows:代码如下:

/**
 * Hide all forms with class="postLink" on page load.
 * Call submit button within a form from an anchor tag
 */
$(document).ready(function() {
  //Hide form(All forms with class="postLink" will be hidden):
  $('.postLink').hide();
 
  var num = 0;
  //Loop over each form with a postLink class
  $("form").each(function(){
    //Add value of submit button as name of text link
    if($(this).hasClass("postLink")){
      //Get value attribute from submit button
      var name = $(this).find('input#submitThis').val();
   
      //Add a uniqueID if the form has no id
      if($(this.id).length == 1){
        this.id='uniqueID'+num;
        num++;
      }
   
      var id = $(this).attr('id');
      //Append a anchor tag after each form that is replaced
      $(this).after("<a id="+id+" class=\"submitLink\" href=\"#\">"+name+"\</a>");
    }
  });

  //Submit button in hidden form by clicking associated anchor tag
  $('.submitLink').click(function(){
    var anchorID = $(this).attr('id');
    //Find the form id that matches the anchor id
    $("form").each(function(){
      if(this.id == anchorID){
        $(this).find('input#submitThis').click();
      } 
    });
    return false;
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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