如何获取用户的表单输入并将其用于事件元素?
2019-05-20
27
我如何获取表单中的输入,并将其应用于事件“Name”和“TheirName”?
尝试了用户提供的各种代码,但均无效。
当我单击“填充名称”按钮时,我尝试将“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>
1个回答
当您执行
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>
j08691
2019-05-20