简体   繁体   中英

Check val of multiple input fields and if there are no empty create new input field

I want when the user selects a file to create additional input for file, but if one of the created input fields is empty to not create a new one

Html:

<div class="pickerColors">
  <div class="color"><input class="selectFile" id="sortpicture" type="file" name="sortpic" />
</div>
</div>

JS:

  function test(){
        var totalFields = $('.selectFile').length;
        for(i=0;i<totalFields;i++){
            if($('.selectFile').eq(i).val()==""){
                return false;

            }


        }
    }
    $('body').on('change', '.selectFile', function () {
        var parent =  $(this).parent().attr("id");
        test();
       if(test() != false){
           $('#'+parent).append('<input class="selectFile" id="sortpicture" type="file" name="sortpic" />');
       }

        });

Found a solution

function isEveryInputEmpty() {
    var notEmpty = true;

    $('.newImage').each(function() {
        if ($(this).val() == '') {
            notEmpty = false;
            return false; // we've found a non-empty one, so stop iterating
        }
    });

    return notEmpty;
}

$('body').on('change', '.newImage', function () {
    var parent =  $(this).parent().attr("id");

   if(isEveryInputEmpty() == true){
        $('#'+parent).append('<input  class="newImage" id="sortpicture" type="file" name="sortpic" />');
    }

    });

There's a few things:

  1. you shouldn't be creating elements with multiple IDs
  2. your inputs should not share the same name if you're sending to the server, you should send multiple values by appending [] to the end of the name
  3. jQuery is unnecessary, if you aren't already loading it for something else, consider avoiding it
  4. you can detect if inputs have a value using the Array.prototype.some method

 document.querySelector('body').addEventListener('change', function(e) { let tgt = e.target if (tgt.classList.contains('selectFile')) { let container = tgt.closest('.color') if (.isEmptyInputAvailable()) { const div = document.createElement('div') div.innerHTML = '<input class="selectFile sortpicture" type="file" name="sortpic[]" />' container.append(div) } } }) function isEmptyInputAvailable() { let inputs = document.querySelectorAll('.sortpicture') return Array.from(inputs).some(input => input.value == '') }
 <div class="pickerColors"> <div class="color"><input class="selectFile sortpicture" type="file" name="sortpic[]" /> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM