[英]How to set minimum value in input html by javascript?
情況描述:我有兩個輸入,第一個是開始時間,第二個是結束時間。
我想說的是:這樣您在結束時間字段(“id_end _”+ i)中輸入的時間不能少於在開始值字段(“id_start _”+ i)中輸入的時間
注意:我警告您不能移動 html 代碼。 我有比 html 代碼中指定的更多的輸入(超過 20),所以循環必須保持
代碼html:
<td id="td01" class="InputsForUserColor1">
<input class="time_sea" type="time" id="id_start_1" />
<input class="time_sea" type="time" id="id_start_2" />
</td>
<td id="td01" class="InputsForUserColor2">
<input class="time_sea" type="time" id="id_end_1" />
<input class="time_sea" type="time" id="id_end_2" />
</td>
我試過:監聽輸入開始變化
var elements_i = document.getElementsByClassName("InputsForUserColor1")
for (var i = 0; i < elements_i.length, i++) {
elements_i.addEventListener("change", function (e) {
document.getElementById("id_end_" + i).setAttribute.(..) = document.getElementById("id_start_" + i).value
});
}
如果我走錯了路請告訴我...
使用document.querySelectorAll(".InputsForUserColor2 > input")
獲取最終輸入的 NodeList。
使用document.querySelectorAll(". InputsForUserColor1 > input")
獲取開始輸入的 NodeList。 使用NodeList.forEach()
迭代 NodeList,並為每個開始元素分配一個事件偵聽器。 使用事件處理程序中起始元素的當前索引來添加最小值。
另外,如果沒有設置結束時間,或者結束時間小於開始時間,也可以根據開始時間更新結束時間。
注意事項:
const ends = document.querySelectorAll(".InputsForUserColor2 > input"); const getMin = timeStr => { const [hour, min] = timeStr.split(':'); return +hour * 60 + +min; }; document.querySelectorAll(".InputsForUserColor1 > input") .forEach((el, i) => { el.addEventListener('change', e => { const value = e.target.value; const end = ends[i]; end.setAttribute('min', value); if(!end.value || getMin(end.value) < getMin(value)) { end.value = value; } }); });
<div id="td01" class="InputsForUserColor1"> <input class="time_sea" type="time" id="id_start_1" /> <input class="time_sea" type="time" id="id_start_2" /> </div> <div id="td01" class="InputsForUserColor2"> <input class="time_sea" type="time" id="id_end_1" max="23:59" /> <input class="time_sea" type="time" id="id_end_2" max="23:59" /> </div>
因此,您基本上需要遍歷所有end date
字段,並將change
事件附加到它們,以檢查匹配的start date
是否高於當前日期。
請注意, elements_i
是一個elements_i
數組,如果您希望在for loop
引用特定元素,則必須將其引用為elements_i[i]
這里有一個開始:
var elements_i = document.getElementsByClassName("InputsForUserColor2")
for (var i = 0; i < elements_i.length, i++) {
elements_i[i].addEventListener("change", function (e) {
const currentID = elements_i[i].getAttribute('id');
const currentEndDate = new Date(elements_i[i].value);
const currentStartDate = new Date(document.getElementById(`id_start_${currentID}`).value);
if (currentStartDate > currentEndDate)
// then do something.....
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.