如何获取表单中的输入,并将其应用到事件“Name”和“TheirName”?
尝试了用户提供的各种代码,但没有成功。
当我单击“填充名称”按钮时,我试图将“名称”和“他们的名称”的输入应用于带有空格 (____) 的元素
function myFunction() {
var str = document.getElementById("myname").innerHTML;
var res = str.replace("_____", "Name");
document.getElementById("myname").innerHTML = res;
}
function myFunction2() {
var str = document.getElementById("theirname").innerHTML;
var res = str.replace("_____", "Their Name");
document.getElementById("theirname").innerHTML = res;
}
<form>
<p>Name<br><input type="text" name="name">
<br>
</p>
<p>Their Name<br><input type="text" name="theirname">
</form>
<p>This is a test for replacing "_____" with "Name" Name and "Their Name" for other name, for sentences with names and greetings.</p>
<p id="myname">Thank you for helping me with those shelves, by the way my name is _____. Would you like to help me with these boxes?</p>
<p id="theirname">There's customer outside who needs help bring a table inside. His name is _____. I'm going to go help him.</p>
<button onclick="myFunction();myFunction2();">Fill Names</button>
最佳答案
当您执行 str.replace("_____", "Name");
时,您将文字字符串 Name
传递给替换函数,而您想要获取文本框的值。您可以使用 document.querySelector()
来实现:
function myFunction() {
var str = document.getElementById("myname").innerHTML;
var res = str.replace("_____", document.querySelector('input[name="name"]').value);
document.getElementById("myname").innerHTML = res;
}
function myFunction2() {
var str = document.getElementById("theirname").innerHTML;
var res = str.replace("_____", document.querySelector('input[name="theirname"]').value);
document.getElementById("theirname").innerHTML = res;
}
<form>
<p>Name<br><input type="text" name="name">
<br>
</p>
<p>Their Name<br><input type="text" name="theirname">
</form>
<p>This is a test for replacing "_____" with "Name" Name and "Their Name" for other name, for sentences with names and greetings.</p>
<p id="myname">Thank you for helping me with those shelves, by the way my name is _____. Would you like to help me with these boxes?</p>
<p id="theirname">There's customer outside who needs help bring a table inside. His name is _____. I'm going to go help him.</p>
<button onclick="myFunction();myFunction2();">Fill Names</button>
关于javascript - 如何获取用户的表单输入并将其用于事件元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56227043/