Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

javascript - Un-focus file input box AFTER file got selected (to validate input)

I have a bootstrap form with a file input box that is checked on the client-site for valid extensions before submitting.

enter image description here

<div class = "container", id="container">
<form id= "fileinput-form" action="/file" method="POST" >
  <div class="form-group col-md-4" >
   <input class="form-control" type="file" accept=".csv,.txt" name="inputfile" aria-label="file example">
  </div>
  <div style="margin-top:10px">
   <input class="btn btn-primary" id="submit-file" type="submit" value="Predict">
  </div>
</form>
</div> 

However, the validation is just triggered after the input box was un-focused (or rather by clicking somewhere). Though, I want to have the validation right after the windows dialog box got closed (file got selected) and without the need to un-focus the input box.

$("#fileinput-form").validate({

      rules:{
          inputfile: {
          required: true,
          extension: true
          }
      },
      messages:{
          inputfile:{
          required: "Please input a file."
          }
      },

 });});

I already tried to add an onchange function, without any success... Is there any solution?

$("#fileinput-form").on("change",function(e) { 
     console.log('file changed'); 
     $("#fileinput-form").trigger('blur');
     /*$("hidden-input").focus();*/
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For anyone who might also struggle with that issue, here is a working solution that does its job pretty well:

  • adding an empty div into the html.

    <div id="eventresponse"> </div>

  • handing over a text into the div.

    $("#inputfile").bind("change",function(){
          $("#eventresponse").text("Input text here");
    });
    
  • adding a new style

    #eventresponse{
      color: red;
      font-style: italic;
      }
    

The eventresponse only gets triggered and pops up as soon as the windows dialog box is closed.

enter image description here

Note: As I am not that familiar with javascript, I implemented the actual validation on the server-site (flask) with an async. fetch call. There is an easier solution in pure javascript, certainly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...