在JavaScript中修改文本框(<input type="text">
或 <textarea>
)的值可以通过多种方式实现。以下是一些基础概念、方法和示例代码:
value
属性来改变文本框的值。<!DOCTYPE html>
<html>
<head>
<title>修改文本框值</title>
</head>
<body>
<input type="text" id="myTextbox" value="初始值">
<button onclick="changeValue()">修改值</button>
<script>
function changeValue() {
var textbox = document.getElementById("myTextbox");
textbox.value = "新值";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>修改文本框值</title>
</head>
<body>
<input type="text" class="myTextbox" value="初始值">
<button onclick="changeValue()">修改值</button>
<script>
function changeValue() {
var textboxes = document.getElementsByClassName("myTextbox");
if (textboxes.length > 0) {
textboxes[0].value = "新值";
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>修改文本框值</title>
</head>
<body>
<input type="text" id="myTextbox" value="初始值">
<button onclick="changeValue()">修改值</button>
<script>
document.getElementById("myTextbox").addEventListener("click", function() {
this.value = "点击后修改的值";
});
</script>
</body>
</html>
window.onload
或将脚本放在</body>
之前。onclick
事件是否正确绑定到按钮上。通过以上方法和示例代码,你可以轻松地在JavaScript中修改文本框的值,并根据具体需求进行调整和扩展。
领取专属 10元无门槛券
手把手带您无忧上云