用javascript替换表单提交上的innerhtml

时间:2014-12-03 16:16:49

标签: javascript html forms

我希望有一个表单询问用户他们的名字,然后欢迎他们访问具有该名称的网站,而无需重定向到其他页面或重新加载。所以基本上用" Welcome NAME"替换表格。点击提交后。

我的代码:



<div id="welcomeText">
	<form onsubmit="changeText()" method="post">
		Name: <input type="text" name="fname">
		<input type="submit">
	</form>
</div>
        
        <script>
            function changeText() {
            var name = document.getElementById(welcomeForm).fname.value;
            var welcome = "Welcome, " + name;
            document.getElementById("welcomeText").innerHTML = welcome;
            }
        </script>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

在尝试访问表单之前,您需要为表单命名,如下所示:

//create the name attribute for the form
<form onsubmit="changeText()" method="post" name="myForm">
    Name: <input type="text" name="fname">
    <input type="submit">
</form>

<script>
        function changeText() {
        //access myForm using document object
        var name = document.name.fname.value;
        var welcome = "Welcome, " + name;
        document.getElementById("welcomeText").innerHTML = welcome;
        }
    </script>

答案 1 :(得分:0)

<div id="welcomeText">
	<form onsubmit="changeText()" method="post" id="welcomeForm">
		Name: <input type="text" name="fname">
		<input type="submit">
	</form>
</div>
        
        <script>
            function changeText() {
            var name = document.getElementById("welcomeForm").fname.value;
            var welcome = "Welcome, " + name;
            document.getElementById("welcomeText").innerHTML = welcome;
            }
        </script>

答案 2 :(得分:0)

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <div id="welcomeText">
        Name: <input type="text" name="fname" id="name">
        <input id="submit" type="submit" onclick="changeText()" onsubmit="changeText()">

</div>

        <script>
            function changeText() {
            var name = document.getElementById("name").value;
            var welcome = "Welcome, " + name;
            document.getElementById("welcomeText").innerHTML = welcome;
            document.getElementById("name").style.display = "none";
            document.getElementById("submit").style.display = "none";
            }
        </script>
    </body>
</html>

尝试此操作将显示“欢迎用户”,并使按钮和输入消失。在这种情况下,您甚至不需要表格。您可以直接从输入中访问该名称,而无需提交表单。

enter image description here

enter image description here

答案 3 :(得分:0)

我们在这里:

<div id="welcomeText">
    <form id="myform" method="post">
        Name: <input type="text" name="fname">
        <input type="submit">
    </form>
</div>

<script>
  var form = document.getElementById("myform");
  form.addEventListener('submit', function (e) {
    e.preventDefault(); // This will prevent submitting the form
    var name = form.fname.value;
    var welcome = "Welcome, " + name;
    document.getElementById("welcomeText").innerHTML = welcome;
  });
</script>