我只想使用具有相同ID的javascript获取所有不同的值。
这是我的输入代码:
<input type="text" id="full" name="full" value="2018-12-06">
<input type="text" id="full" name="full" value="2018-12-14">
<input type="text" id="full" name="full" value="2018-12-18">
当我警告输入的ID时,它仅显示2018-12-06。我想禁用jquery datepicker,但2018年12月6日是唯一的读取。
这是我的日历。
和我的JavaScript代码:
var x = (document.getElementById('full').value);
var array = ["2018-12-25", "2019-01-01", x]
我想禁用所有具有相同ID的值,如上文所述,
答案 0 :(得分:2)
ID必须是唯一。您应该为每个元素添加一个类,然后使用getElementsByClassName
。
因为该方法返回一个节点列表以获取需要迭代的每个输入值。对于这两个示例,我都使用过map
,但是您可能会更容易使用for/loop
或forEach
。
const full = document.getElementsByClassName('full');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" class="full" name="full" value="2018-12-06">
<input type="text" class="full" name="full" value="2018-12-14">
<input type="text" class="full" name="full" value="2018-12-18">
一种替代方法是使用querySelectorAll
。这使用CSS选择器,因此您可以通过元素的属性来精确定位元素:
const full = document.querySelectorAll('[name="full"]');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" class="full" name="full" value="2018-12-06">
<input type="text" class="full" name="full" value="2018-12-14">
<input type="text" class="full" name="full" value="2018-12-18">
答案 1 :(得分:1)
ID用作单个标识符。因此,对多个元素使用相同的ID是非法的。要获取多个元素的值,请使用class而不是id。
您可以使用getElementsByClassName()
函数来读取具有相同类名的所有元素的值
使用jQuery替代getElementsByClassName()
var l = $('.full').length;
//Initialize default array
var result = [];
for (i = 0; i < l; i++) {
//Push each element to the array
result.push($('.full').eq(i).val());
}
//print the array or use it for your further logic
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="full" value="2018-12-06">
<input type="text" class="full" value="2018-12-14">
<input type="text" class="full" value="2018-12-18">
答案 2 :(得分:0)
您无法创建具有相同ID的元素,如果要使用javascript从另一个元素获取所有不同的值,则可以使用ClassName
<input type="text" class="full" name="full" value="2018-12-06">
<input type="text" class="full" name="full" value="2018-12-14">
<input type="text" class="full" name="full" value="2018-12-18">
var x = document.getElementsByClassName('full');