提交表单后,文本区域值保持不变

Textarea value remain the same after submitting a form

本文关键字:区域 表单 文本 提交      更新时间:2023-09-26

我以前的问题已经解决,现在我需要询问如何在提交表单后防止文本区域重置其输入。这是jsFiddle:http://jsfiddle.net/rz4pnumy/

我应该更改HTML中的表单吗?

<form id="form1" method="GET">

(表单没有进入php文件或其他任何文件,我使用它来提交文本区域输入,并使用我使用jQuery创建的变量在同一页面上创建一段)或者JS里的什么?

$(document).ready( function () {
  $('#form1').on('submit', function (event) {
    // If the form validation returns false, block the form from submitting by 
    // preventing the event's default behaviour from executing.
    if (!validate()) {
        event.preventDefault();
    }
    if(validate()) {
      var adjective1 = $('#adjective1').val();
      var adjective2 = $('#adjective2').val();
      var pluralnoun = $('#plural-noun').val();
      var verb1 = $('#verb1').val();
      var edibleobject = $('#edible-object').val();
      var monster1 = $('#monster1').val();
      var adjective3 = $('#adjective3').val();
      var monster2 = $('#monster2').val();
      var verb2 = $('#verb2').val();
      $('body').append(
        '<div id="para">' +
          '<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
          'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
          'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' + 
          'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
          'on a table surrounded by a knot of curious people. </p>' +
        '</div>'
        );
    }
});
function validate() {
  var success = true;
  $('.input').each(function(i, item) {
      if ($(item).val() === "") 
      {
         console.log("Missing textarea input");
         success = false;
         $(item).attr("style","border:1px solid red;");
         //note it will overwrite your element style in all Input class
      }
      else
      {
         $(item).removeAttr('style')
         // to remove border 
     }
   });
    return success;
}
});

按下提交按钮后,内容被清空,我只看到一瞬间完成的段落。

无论validate是否通过,都需要阻止默认事件处理程序执行,因此需要删除event.prventDefault()调用周围的if语句。preventDefault是阻止提交和重新加载页面的函数。

此外,你的Fiddle没有设置为jQuery(它被设置为没有库),所以这可能也导致了你在测试过程中出现问题。

以我所说的为例编辑:

$('#form1').on('submit', function (event) {
    // block the form from submitting by 
    // preventing the event's default behaviour from executing.
    event.preventDefault();
    if(validate()) {
        var adjective1 = $('#adjective1').val();
        var adjective2 = $('#adjective2').val();
        var pluralnoun = $('#plural-noun').val();
        ... etc ...

我会使用php,将一个变量设置为文本区域的GET值,并将文本区域的值设置为变量