【问题标题】:Trying to create a vanishing form once submitted using javascript尝试使用javascript提交后创建消失的表单
【发布时间】:2015-03-18 14:30:44
【问题描述】:

我正在尝试为一个小型网络应用程序创建一个消失的表单。目的是一旦提交表单,就会显示一个新表单。我的代码目前可以正常工作,但它会持续几毫秒,然后恢复为原始形式。

首先是主要形式:

<div id="question">
<form action="" method="POST" name="quest" id="quest" onsubmit="Vanish();">
<textarea name="question" class="form-field" placeholder="Ask your      question..."></textarea><br><br>
<input type="image" src="images/submit.png" name="qsubmit" >
</form>
</div>

然后是我想用上面的表格替换:

<div id="email" style="display:none;">
<form action="" method="POST" id="email">
<input type="text" name="fName" placeholder="First Name" class="form-field">
<input type="text" name="sName" placeholder="Second Name">
<input type="text" name="email" placeholder="Email">
<input type="image" src="images/submit.png" name="esubmit" onclick="submitForm()">
</form>
</div>

然后我有一个 javascript 函数(我仍然是 javascript 的新手)。

function Vanish() {

// Specify the id of the form.
var IDofForm = "quest";

// Specify the id of the div containing the form.
var IDofDivWithForm = "question";

// Specify the id of the div with the content to replace the form with.
var IDforReplacement = "email";

// This line submits the form.
document.getElementById(IDofForm).submit();

// This replaces the form with the replacement content.
document.getElementById(IDofDivWithForm).innerHTML = document.getElementById(IDforReplacement).innerHTML;
};

我正在努力实现: 一个简单的表格交换。一旦提交了一个表格,另一个表格就会出现。 我发现一个与我相似的问题是:Content disappears immediately after form submitted and function runs

但是,它只是使表单消失而不是被替换。 提前致谢。

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    提交表单后,页面将刷新。因此,在您的函数中,您必须防止默认行为并通过 AJAX 提交表单。

    如果需要根据第一个表单的响应显示第二个表单,则在 AJAX 中触发 readyState 事件后执行表单替换逻辑。

    function Vanish(event) {
    
    event.preventDefault();
    
    // Specify the id of the form.
    var IDofForm = "quest";
    
    // Specify the id of the div containing the form.
    var IDofDivWithForm = "question";
    
    // Specify the id of the div with the content to replace the form with.
    var IDforReplacement = "email";
    
    // This line submits the form.
    
    // Get all the form elements and submit the form using ajax manually.
    // document.getElementById(IDofForm).submit();
    
    // This replaces the form with the replacement content.
    
    // Put this code inside the success of ajax request
    document.getElementById(IDofDivWithForm).innerHTML = document.getElementById(IDforReplacement).innerHTML;
    };
    

    在您的代码中:

    <form action="" method="POST" name="quest" id="quest" onsubmit="Vanish(event);">
    

    【讨论】:

    • 你需要实现ajax来防止页面刷新,然后显示第二个div。让我为你设置一个 jsfiddle
    • 顺便说一句,您正在测试哪个浏览器?
    • 我从来没有做过ajax。是的,一个jsfiddle会帮助谢谢你。我在谷歌浏览器上
    • 你先生是个天才!非常感谢
    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多