简体   繁体   English

如何将HTML元素的文本设置为表单文本提交?

[英]How can I set the text of an HTML element to a form text submission?

I'm creating a basketball scoring app and I would like the team names to be custom so I created a form so you could submit new names. 我正在创建一个篮球评分应用程序,我希望团队名称是自定义的,所以我创建了一个表单,以便您可以提交新名称。 However, when I click the submit button nothing happens but a white flicker on the page. 但是,当我单击提交按钮时,没有任何反应,但页面上出现白色闪烁。 I am just opening the file inside of chrome from my file manager. 我只是从我的文件管理器中打开chrome里面的文件。

Here is what I need to rename: 这是我需要重命名的内容:

<span class="teamname" id="1">Team 1</span>

Here is the form that I have: 这是我的表格:

 <form id="myForm">
<input id="name1" maxlength="6" type="text">
<button type="submit" onclick="updateFunction()">Update Team Names</button>
</form>

Finally, here is my JavaScript: 最后,这是我的JavaScript:

function updateFunction() {
var newname1 = document.getElementById("myForm").elements.namedItem("name1").value;
document.getElementById('1').innerHTML = newname1;
}

HTML forms expect an action attribute that signifies where the form data should be sent, eg HTML表单期望一个action属性,表示应该发送表单数据的位置,例如

<form action="/login"></form>

HTML5 doesn't require you to specify the action , but not specifying it defaults to the same page you are on. HTML5不要求您指定action ,但不指定它默认为您所在的同一页面。 So in your case submitting the form basically reloads the page. 因此,在您的情况下,提交表单基本上会重新加载页面。 To block that behaviour, you can use a falsy javascript value . 要阻止该行为,您可以使用虚假的javascript值

It's also better form to set the submission logic in the form element, not the submit button. 在表单元素中设置提交逻辑也是更好的表单,而不是提交按钮。

So here's how you should change your code: 所以这是你应该如何改变你的代码:

<form id="myForm" action="javascript:void(0)" onsubmit="updateFunction()">
    <input id="name1" maxlength="6" type="text">
    <button type="submit">Update Team Names</button>
</form>

The button tag should be located outside the HTML form. 按钮标记应位于HTML表单之外。 So, the form should look like: 因此,表单应如下所示:

 <form id="myForm">
 <input id="name1" maxlength="6" type="text">
 </form>
 <button type="submit" onclick="updateFunction()">Update Team Names</button>

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

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