我无法让表单提交到html / JavaScript中工作

时间:2017-12-22 15:20:00

标签: javascript html text submit

我尝试了很多不同的东西以及搜索和谷歌搜索,但我只是看不出如何使一些非常基本的代码工作。请让用户提交文本输入。

下面这段代码应该只改变第一段说工作。

translation

理想情况下,我可以将输入的内容保存到变量中,然后显示输入的名称,但截至目前我无法正常工作。甚至没有将段落更新为sy工作的基本功能。

2 个答案:

答案 0 :(得分:0)

文本框没有onsubmit个事件。您可以在表单上使用该事件(我不会在您的问题中看到)。虽然不是必需的,但我还会添加一个提交按钮,因为这是一个更好的设计。

在JavaScript中为ParaOne分配初始值也很浪费,只需在元素中键入值即可。

<form onsubmit="Test();">
  <p id="ParaOne">Enter Name:</p>
  <input type="text" id="TextInput">
</form>
<script>
  function Test() {
    document.getElementById("ParaOne").innerHTML = "Working";
  }
</script>

重要提示:虽然上面的代码是你应该怎么做的,但我真的不明白这一点。在更改ParaOne的文本后,表格将立即提交,这将重新加载页面,您将再次看到初始值(并且可能认为它没有工作)。它会工作但速度非常快,所以没有人会真正看到它,那么重点是什么?

答案 1 :(得分:-1)

您可以使用javascript方法onchangeonkeydown来触发输入字段的输入,您无需提交表单。但是如果你只需要我添加了这个例子。我使用jQuery代替plain javascript来编写函数,因为现在它们实际上变成了one-line函数。

onchange将等待用户按Enter键或输入元素松散焦点以调用该函数。

onkeydown会在每次按键时调用该功能。

e.preventDefault()取消元素的默认操作,在这种情况下是提交操作,并允许我们通过代码决定是否提交。

以下是一些javascript/jQuery测试函数和一个示例HTML文件,因此您可以测试哪种方法最适合您。

编辑:我添加了一些关于如何将输入字段的当前值存储到变量中的示例

// get the Value of input element directly into a variable
var myVariable = $('#theInput_1').val();

// myVariable will return empty string since the input element is empty
console.log('This is the starting value of the 1st input element: ' + myVariable);


// Function for onkeydown test
function testKeyDown()
{
  // stored in a variable which is not available outside the function
  var myVariable = $('#theInput_1').val();
  $('#paraOne').text(myVariable);
  
  // test output - $('#theInput_1').val() will return empty
console.log('This is the changed value of the 1st input element: ' + myVariable);
}

// Function for onchange test
function testOnChange()
{
  $('#paraTwo').text($('#theInput_2').val());
}

// Function for submit test
$( "#submit" ).on( "click", function(e)
{
  e.preventDefault(); // Prevents default action of submit
  $('#paraThree').text($('#theInput_3').val());
});
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>

<p id="paraOne">This text will be replaced on success.</p>
<input type="text" id="theInput_1" onkeydown="testKeyDown();" size="50" value="" placeholder="onkeydown test" />

<p id="paraTwo">This text will be replaced on success.</p>
<input type="text" id="theInput_2" onchange="testOnChange();" size="50" value="" placeholder="onchange test" />

<p id="paraThree">This text will be replaced on success.</p>
<form>
<input type="text" id="theInput_3" size="50" value="" placeholder="form submit test" />
<input type="submit" id="submit" value="Submit me" />
</form>

</body>
</html>