技术文摘
JavaScript 如何获取 input 输入框内容
JavaScript 如何获取 input 输入框内容
在前端开发中,使用 JavaScript 获取 input 输入框的内容是一项基础且常见的操作。无论是简单的表单验证,还是构建复杂的交互应用,这一技能都至关重要。
对于文本输入框(type="text"),获取其内容十分直接。通过 document.getElementById 方法选中输入框元素,再使用其 value 属性即可获取输入的值。例如,HTML 中有一个 id 为 "inputBox" 的文本输入框:<input type="text" id="inputBox">。在 JavaScript 中,我们可以这样获取它的内容:
const inputElement = document.getElementById('inputBox');
const inputValue = inputElement.value;
console.log(inputValue);
密码输入框(type="password")获取内容的方式与文本输入框相同。因为从底层原理来说,它们都属于 input 元素,只是在显示形式上有所区别。比如有一个密码输入框 <input type="password" id="passwordBox">,获取其内容的代码如下:
const passwordElement = document.getElementById('passwordBox');
const passwordValue = passwordElement.value;
单选框(type="radio")和复选框(type="checkbox")获取内容的方式稍有不同。对于单选框,首先要确保它们具有相同的 name 属性,以便形成一个单选组。例如:
<input type="radio" id="male" name="gender" value="male">男
<input type="radio" id="female" name="gender" value="female">女
在 JavaScript 中获取选中单选框的值,可以使用以下代码:
const radioElements = document.querySelectorAll('input[type="radio"]');
let selectedValue;
radioElements.forEach((radio) => {
if (radio.checked) {
selectedValue = radio.value;
}
});
复选框则可以选中多个选项。HTML 代码示例:
<input type="checkbox" id="apple" name="fruits" value="apple">苹果
<input type="checkbox" id="banana" name="fruits" value="banana">香蕉
获取选中复选框的值的 JavaScript 代码如下:
const checkboxElements = document.querySelectorAll('input[type="checkbox"]');
const selectedValues = [];
checkboxElements.forEach((checkbox) => {
if (checkbox.checked) {
selectedValues.push(checkbox.value);
}
});
下拉框(select 元素)获取内容也较为简单。假设 HTML 中有一个下拉框:
<select id="citySelect">
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
</select>
在 JavaScript 中可以这样获取选中的值:
const selectElement = document.getElementById('citySelect');
const selectedCity = selectElement.value;
掌握这些获取 input 输入框内容的方法,能为前端开发工作打下坚实的基础,帮助开发者实现更多交互功能和业务逻辑。
TAGS: JavaScript input输入框 获取内容方法
- Python 中 POST 请求的剖析
- Go 语言逃逸分析浅析
- Go 语言中的包管理方式
- Golang Slice 常见性能优化方法汇总
- Python 中 geopandas 库安装问题的解决之道
- Gin 框架中跨域问题的多种解决之道
- Python 读取 PDF 中文字与表格的方法
- Python 中 index 的用法全解与注意要点
- Golang 高并发中的本地缓存深度解析
- Go channel 批量读取数据的方法
- Golang 日志库 ZAP(uber-go zap)示例深度剖析
- Python 中 405 错误的成因及解决办法
- Python 借助 BeautifulSoup(bs4)解析复杂 HTML 内容
- Python 与 OpenCV 实时目标检测实例的使用详解
- Go channel 批量读取数据示例的详细解读