Why is my jQuery/Javascript function not being called correctly with onsubmit?

前端 未结 1 1738
孤城傲影
孤城傲影 2021-01-28 16:57

I have this jQuery function that is using another jQuery library called html5csv.js (which explains some of the CSV stuff you will see)

Here is it:

funct         


        
相关标签:
1条回答
  • 2021-01-28 17:25

    html5csv puts a event handler on the file input so it only triggers when a file is added so you need to set a valid flag somewhere and then check it before submitting

    function checkValidCSV(e) {
        var isValid = jQuery("#form-step2").data("hasValidData");
        if( typeof(isValid) != "undefined" && isValid ) {
            jQuery("#form-step2").submit();
        } else {
            //Do whatever invalid data cals you want to do here
            alert("csv file was invalide so i am not submitting the form");
            e.preventDefault();
        }
    }
    
    function csvFileLoaded(e,D) {
        if (e) {
            return console.log(e); 
            alert("Sorry, an error occured");
        }
    
        var s = "";
        for (var i = 0; i <= D.rows.length - 1; i++) {
            s +=D.rows[i].join(',');
            s += "\n";
        }
        var fullString = s;
        if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString)){
            console.log("Valid Data");
            jQuery("#form-step2").data("hasValidData",true);
        } else {
            console.log("Invalid Data");
            jQuery("#form-step2").data("hasValidData",false);
        }
    }
    
    jQuery(document).ready(function() {
        CSV.begin("#upload_csv").go(csvFileLoaded);
        jQuery("#newQuizID").click(checkValidCSV);
    });
    
    0 讨论(0)
提交回复
热议问题