在JavaScript中获取表单(form)中选中的行,通常涉及到处理如<select>
元素的多选情况,或者是在表格(table)中通过复选框(checkbox)选择行。以下是相关的基础概念、方法及示例代码:
<select>
元素的多选如果使用<select>
元素并启用了多选(multiple
属性),可以通过遍历选项来获取选中的值。
示例代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>获取选中的行</title>
</head>
<body>
<form id="myForm">
<label for="fruits">选择水果:</label>
<select id="fruits" name="fruits" multiple>
<option value="苹果">苹果</option>
<option value="香蕉">香蕉</option>
<option value="橙子">橙子</option>
</select>
<button type="button" onclick="getSelectedOptions()">获取选中项</button>
</form>
<script>
function getSelectedOptions() {
const selectElement = document.getElementById('fruits');
const selectedOptions = [];
for (let i = 0; i < selectElement.options.length; i++) {
if (selectElement.options[i].selected) {
selectedOptions.push(selectElement.options[i].value);
}
}
console.log('选中的水果:', selectedOptions);
alert('选中的水果: ' + selectedOptions.join(', '));
}
</script>
</body>
</html>
优势:
在表格中,通常使用复选框来选择行。可以通过遍历表格行,检查复选框是否被选中,从而获取选中的行数据。
示例代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>获取表格选中行</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 8px;
}
</style>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>选择</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="rowCheckbox"></td>
<td>张三</td>
<td>25</td>
</tr>
<tr>
<td><input type="checkbox" class="rowCheckbox"></td>
<td>李四</td>
<td>30</td>
</tr>
<tr>
<td><input type="checkbox" class="rowCheckbox"></td>
<td>王五</td>
<td>28</td>
</tr>
</tbody>
</table>
<button onclick="getSelectedRows()">获取选中行</button>
<script>
function getSelectedRows() {
const checkboxes = document.querySelectorAll('.rowCheckbox:checked');
const selectedRows = [];
checkboxes.forEach(checkbox => {
const row = checkbox.closest('tr');
const cells = row.cells;
selectedRows.push({
name: cells[1].innerText,
age: cells[2].innerText
});
});
console.log('选中的行:', selectedRows);
alert('选中的行: ' + JSON.stringify(selectedRows));
}
</script>
</body>
</html>
优势:
multiple
属性或选择器错误。<select>
元素有multiple
属性,并且JavaScript选择器正确指向该元素。通过以上方法和示例代码,您可以在JavaScript中有效地获取表单或表格中的选中行,并根据具体需求进行相应的处理和操作。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云