簡體   English   中英

CloneNode 如果輸入的所有字段都填寫了,但字段未填寫時仍然克隆

[英]CloneNode if all the fields input is filled in still cloning when fields are not filled in

如果未填寫所有字段輸入和選定框,我希望我的按鈕不要克隆我的字段。

HTML

<fieldset id="schedule-items">
        <legend>Horários disponíveis 
            <button type="button" id="add-time" onclick="addButton()">+Novo horário</button>
        </legend>
        <div class="schedule-item">
            <div class="select-block">
                <label for="weekday">Dia da semana</label>
                <select name="weekday[]" required="true">
                    <option id="select" value="select" selected>Selecione uma opção</option>
                    {%for weekday in weekdays %}
                    <option value="{{loop.index0}}">{{weekday}}</option>
                    {%endfor%}
                </select>
            </div>
            <div class="input-block">
                <label for="time_from">Das</label>
                <input type="time" name="time_from[]" required>
            </div>
            <div class="input-block">
                <label for="time_to">Ate</label>
                <input type="time" name="time_to[]" required>
            </div>
        </div>
    </fieldset>
</form>

JS

function cloneField(){
    const newFieldContainer = document.querySelector(".schedule-item").cloneNode(true)
    let fields = newFieldContainer.querySelectorAll('input')
    fields.forEach(function(field){
        field.value = ""
    })
    document.querySelector("#schedule-items").appendChild(newFieldContainer)
  
}

function addButton(){
    const selected = document.getElementById('select').selected
    console.log(selected)
    const scheduleItems = document.querySelector('#schedule-items')
    console.log(scheduleItems)
    let inputs = scheduleItems.querySelectorAll('input')
    inputs.forEach(function(input){
        if(selected == true || input.value == ""){
            alert('Please select a day and time of the week')
        }else{
            let button = document.querySelector("#add-time")
            button.addEventListener('click',cloneField)
    }   
    })
    }
          

目前,當我第一次嘗試單擊按鈕時,它會向我發出警報消息,但一旦克隆了第二個字段克隆,即使我需要填寫所有字段輸入並進行特定選擇。

您可以使用Array#some遍歷所有元素並檢查是否有任何元素未填充,而不是像當前那樣僅檢查第一個元素。

if(!selected || [...inputs].some(input=>input.value==='')){
    alert('Please select a day and time of the week')
} else {
    let button = document.querySelector("#add-time")
    button.addEventListener('click',cloneField)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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