How to check input file is empty, and also display an alert if png format is selected using jquery

后端 未结 4 1416
谎友^
谎友^ 2021-02-07 11:23

I have got an input file upload , need to check which file is uploaded / if no file is selected by the client using jquery.



        
相关标签:
4条回答
  • 2021-02-07 11:30

    Testing for...

    $('#file1')[0].files.length == 0
    

    ...is working for me in Chrome. The jQuery is actually not even necessary as the raw HTML element (returned by the [0] on the jQuery object) gives access to the files list.

    0 讨论(0)
  • 2021-02-07 11:31

    Have you made any attempt at doing this?

    $('input[type="file"]').val()
    
    0 讨论(0)
  • 2021-02-07 11:41

    See the sample I have created:

    http://jsfiddle.net/G7xke/


    <form>
    <input type="file" name="files" id="file1" style="color:White" />
    <input type="submit" value="Create" />
    </form>
    <button value="check" id="check" name="check" >check</button>
    

    And JavaScript:

    $("#check").click(function(){
        var fileName = $("#file1").val();
        if(fileName.lastIndexOf("png")===fileName.length-3)
            alert("OK");
        else
            alert("Not PNG");
    })
    
    0 讨论(0)
  • 2021-02-07 11:54

    This demo works in IE9 + Chrome:

    http://jsfiddle.net/brdFq/
    

    using Jquery, you get the val();

    a quick implementation here:

    function hasFile(selector){
        //if there is a value, return true, else: false;
        return $(selector).val()? true: false;
    }
    
    0 讨论(0)
提交回复
热议问题