添加输入并检查接下来的几次输入

时间:2018-11-06 04:38:32

标签: jquery

添加输入,并在接下来的几次输入中检查是否为空,如果其中之一为空,则不要添加新输入。第一次单击并检查下一个是否为空时,如何添加输入?如果添加的输入之一为空,则不要添加下一个?

<label class="button">New</label>
  <div class="table-title">
    <div class="table_narrow">Name</div>
    <div class="table_narrow">Amount</div>
    <div class="table_narrow">Time</div>
</div>
<div class="table-list">
</div>

功能本身

$(".button").click(function () {
    $(".table-list").prepend('<div class="table-row">' +
        '<input class="table-list" name="Name[]" type="text">' +
        '<input class="table-list" name="Amount[]" type="number">' +
        '<input class="table-list" name="Date[]" type="date">' +
        '<label class="table-btn></label>' +
        '</div>');
});

2 个答案:

答案 0 :(得分:3)

在添加前搜索所有现有输入。

$(".button").click(function () {
    var empty_found = false;
    $(".table-list input").each(function() {
        if (this.value == "") {
            empty_found = true;
            return false;
        }
    });
    if (empty_found) {
        alert("Fill in all rows before adding another row");
    } else {
        $(".table-list").prepend('<div class="table-row">' +
            '<input class="table-list" name="Name[]" type="text">' +
            '<input class="table-list" name="Amount[]" type="number">' +
            '<input class="table-list" name="Date[]" type="date">' +
            '<label class="table-btn></label>' +
            '</div>');
    }
});

答案 1 :(得分:0)

检查所有第一行输入(如果有)是否未填写。该代码使用.filter()来计数未填充(空)的输入。

$(".button").click(function () {
    //Get all first row inputs, if any (see inputs.length)
    var inputs = $('div.table-row:first input');
    
    //If inputs found, get number unfilled, otherwise 0
    var numUnfilled = inputs.length ? inputs.filter(function() {
        return !this.value.length;
    }).length : 0; 
    
    //If numUnfilled is zero, add row; otherwise do not add row
    numUnfilled ||
    $(".table-list").prepend('<div class="table-row">' +
        '<input class="table-list" name="Name[]" type="text">' +
        '<input class="table-list" name="Amount[]" type="number">' +
        '<input class="table-list" name="Date[]" type="date">' +
        '<label class="table-btn></label>' +
        '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label class="button">New</label>
  <div class="table-title">
    <div class="table_narrow">Name</div>
    <div class="table_narrow">Amount</div>
    <div class="table_narrow">Time</div>
</div>
<div class="table-list">
</div>