带有javascript的HTML必需函数,该必需函数不起作用


HTML required functions with javascript which required function doesnt work

谁能帮我这个必需的功能不起作用。 我正在我的HTML/PHP网页中上传图片,在上传图片之前,我设置了一个下拉选项,即上传或不上传,这是我的代码:

<script>
    function papeles()
    {
        var x = document.getElementById('tagoan1').value;
        if (x == "YES")
        {
            //  alert('aaaa');
            $('#imgInp').addClass("required");
            $('#imgInp').removeClass("hidden");
            $('#blah').removeClass("hidden");
        } else
        {
            //alert('bbbbb');
            $('#imgInp').addClass("hidden");
            $('#imgInp').removeClass("required");
            $('#blah').addClass("hidden");
        }
    }
</script>
<div class="col col-sm-5">
    <label>Attachment </label>
    <select class="form-control" id="tagoan1" name="taguan" onchange="papeles()" required disabled>
        <option value="">With Attachment?</option>
        <option value="YES">Yes</option>
        <option value="NO">No</option>
    </select>
</div>
<div class="row text-center">
    <div class="col col-sm-6">
        <div class="form-group" style="margin:0;">
            <input type='file' name="image" id="imgInp" value="" class="hidden required btn btn-block btn-sm" style="padding-left:3em;width:300px"/>
        </div>
        <img id="blah" src="customer/tagoan/images/noimage.png"  height="200px" width="300px" name="tae" border-color="white" placeholder="" class="hidden"/>
    </div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script>
         function readURL(input) {
             if (input.files && input.files[0]) {
                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $('#blah').attr('src', e.target.result);
                 }
                 reader.readAsDataURL(input.files[0]);
             }
         }
         $("#imgInp").change(function () {
             readURL(this);
         });
</script>

问题是,当我单击是但没有选择文件时,图片仍然会提交它不应该提交,因为需要添加类来解决这个问题。

隐藏输入时,不会将其从页面中删除。因此,文件输入将保留在表单中,无论是否隐藏,都会进行汇总。您需要从 DOM 中删除输入:

    if (x == "YES")
    {
        $('#imgInp').remove() // file input gone
        $('#blah').removeClass("hidden");
    } else
    {
        //you should add an ID to the parent of imgInp instead of referring as .form-group
        $('.form-group').prepend("<input type='file' name='image' id='imgInp' value='' class='required btn btn-block btn-sm' style='padding-left:3em;width:300px'/>")
        $('#blah').addClass("hidden");
    }

如果你只使用jQuery的.hide().show()可以吗?