如何获取表单中的输入并将其应用于事件“名称”和“ 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>
答案 0 :(得分:1)
当您执行str.replace("_____", "Name");
时,您是将文字字符串Name
传递给replace函数,而您想获取文本框的值。您可以为此使用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>