我是javascript的新手,我在w3schools.com中显示了这个 - 在搜索框中输入密码将显示在<p>
标记 !!怎么做 ?任何帮助赞赏。提前致谢
HTML:
<form class="form1" role="search" method="get" action="search-pincode.html">
<input class="pincode1" type="number" placeholder="Enter Postcode" id="user-pincode">
<button class="submit" type="submit" formaction="search-pincode.html" onclick="myFunction()">Check</button>
</form>
JS SCRIPT:
<script>
function myFunction() {
var x = document.getElementById("user-pincode").value;
document.getElementById("user-pincode-show").innerHTML = x;
}
</script>
OUTPUT:search-pincode.html
<h1 class="search-h1-contact">
Yes, we install CCTV in <p id="user-pincode-show"></p>
</h1>
答案 0 :(得分:3)
首先,您不会看到足够长的结果,因为点击按钮后,您将被重定向到search-pincode.html
。尝试将type="submit"
更改为type="button"
function myFunction() {
var x = document.getElementById("user-pincode").value;
document.getElementById("user-pincode-show").innerHTML = x;
}
&#13;
<form class="form1" role="search" method="get" action="search-pincode.html">
<input type="number" placeholder="Enter Postcode" id="user-pincode">
<button type="button" onclick="myFunction()">Check</button>
</form>
<h1 class="search-h1-contact">
Yes, we install CCTV in
<p id="user-pincode-show"></p>
</h1>
&#13;
如果你计划的是将输入的值传递给search-pincode.html
,并且user-pincode-show
在其中,那么使用JavaScript不是正确的方法
答案 1 :(得分:2)
如果要避免重定向表单子目录,可以使用EventTarget.addEventListener()声明一个事件侦听器来处理click事件并在函数处理程序中调用e.preventDefault
。
另请注意,无需在formaction="search-pincode.html"
元素中添加button
,因为form
具有属性action="search-pincode.html"
最后一件事:在h1
元素中,您可以更好地使用span
元素而不是p
。
<h1>Yes, we install CCTV in <span id="user-pincode-show"></span></h1>
代码示例:
document
.querySelector('button.submit')
.addEventListener('click', function (e) {
e.preventDefault();
var x = document.querySelector('#user-pincode');
document.querySelector('#user-pincode-show').innerHTML = x.value;
});
<form class="form1" role="search" method="get" action="search-pincode.html">
<input class="pincode1" type="number" placeholder="Enter Postcode" id="user-pincode">
<button class="submit" type="submit">Check</button>
</form>
<h1>Yes, we install CCTV in <span id="user-pincode-show"></span></h1>
答案 2 :(得分:1)
function myFunction() {
var x = document.getElementById("user-pincode");
document.getElementById('user-pincode-show').innerHTML = x.value;
}
&#13;
<form class="form1" role="search" method="get" action="search-pincode.html">
<input type="number" placeholder="Enter Postcode" id="user-pincode">
<button type="button" onclick="myFunction()">Check</button>
</form>
<h1 class="search-h1-contact">
Yes, we install CCTV in
<p id="user-pincode-show"></p></h1>
&#13;