0

I have this input file:

Razor:

@Html.TextBox("archivo", "", new { type = "file",id = "archivo" }

Html:

<input id="archivo" name="archivo" type="file" value="">

I want to capture message if value of input is null when I press button:

<button type="button" id="btnCargarCsv" class="btn btn-primary">Cargar</button>

So on clic function I try to send message as:

 $("#btnCargarCsv").on("click", function () {
        if ($('#archivo').val() == null) {
            $('#resultado').html('you need to select file');
        }
        var data = new FormData();
        data.append("archivo", $("#archivo")[0].files[0]);

        $.ajax({
            "type": "POST",
            "url": "/Configuracion/CargaCSV",
               ...

But it just don't throw message when input come null beacuse it don't hit:

$('#resultado').html('you need to select file');

like input is not null. What am I doing wrong?

Traveler
  • 191
  • 1
  • 10
  • You can simply use `if ($('#archivo').val()) { // ajax call } else { // display message }` –  Feb 07 '18 at 06:13

5 Answers5

4

Verify using blank string instead of null..

Also look into : Link for difference between null and empty

And Possible : Link

$("#btnCargarCsv").on("click", function () {

    if ($('#archivo').val() == '') {
        $('#resultado').html('you need to select file');
        return;
    }

    var data = new FormData();
    data.append("archivo", $("#archivo")[0].files[0]);

    $.ajax({
        "type": "POST",
        "url": "/Configuracion/CargaCSV",
            ...
Vishnu Bhadoriya
  • 1,655
  • 1
  • 20
  • 28
Kapil Barad
  • 716
  • 7
  • 17
1

Check Length.

if ($('#archivo').get(0).files.length === 0) {
       $('#resultado').html('you need to select file');
}
4b0
  • 21,981
  • 30
  • 95
  • 142
0

Give a try ..!

 if ($('#archivo').get(0).files.length === 0) {
        //console.log("No files selected.");
        //alert("Please select file..");
         $('#resultado').html('you need to select file');

    }

Hope this helps..!

0

I dont know why your code isnt working. But the file validation (null or not) can be done by simply adding a required tag to your html.

<input... [whatever be your type and value].. required/>

Validation would be done by this piece of code.

Maybe its not null,, try it with "" and check...

if($('#archivo').val()=="")
{
      //print your message
}
else
      //your logic goes here
0

You can Just check if a variable has a true value or not. In your case it will be

if(!$('#archivo').val()) {
  $('#resultado').html('you need to select file');
    return;
}

It will evaluate to false if value is false, 0, empty string, NaN, undefined, null

artista_14
  • 674
  • 8
  • 22