簡體   English   中英

如何通過javascript在輸入html中設置最小值?

[英]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,並為每個開始元素分配一個事件偵聽器。 使用事件處理程序中起始元素的當前索引來添加最小值。

另外,如果沒有設置結束時間,或者結束時間小於開始時間,也可以根據開始時間更新結束時間。

注意事項

  1. 對於要分配的最小值。 你需要完全感受開始輸入
  2. 您還需要在最后設置一個最大值。 如果結束將低於最小值,它將循環回到最大值。

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM