PHP停止表单重新加载显示错误Js

PHP Stop Form Reload Show Error Js

本文关键字:加载 显示 错误 Js 表单 新加载 PHP      更新时间:2023-09-26

如果"fileToUpload"为空,我想显示我的错误(用js显示错误),如果"fileToUpload"是空,我想停止重新加载页面

<form method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input class='new_post' type="submit" value="Upload Image" name="submit">
</form>
$('.new_post').click(function() {
    var get_photo = $('#fileToUpload').get(0).files.length;
    // If 0 file show error 
    if (get_photo == 0) {
        openandclose('.error_box' , 'emptyyyy.', 1700);
        $('.error_box').focus();
        return false;
    }
});

向表单添加一个id,如<form method="post" enctype="multipart/form-data" id="myform">,并在javascript中将检查函数作为回调附加到表单提交事件,而不是像$('#myform').submit()那样的按钮单击事件。

$('#myform').submit(function() {
  var get_photo = $('#fileToUpload').get(0).files.length;
  // If 0 file show error 
  if (get_photo == 0) {
    /*
    openandclose('.error_box', 'emptyyyy.', 1700);
    $('.error_box').focus();
    */
    alert("EMPTY!!");
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" id="myform">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input class='new_post' type="submit" value="Upload Image" name="submit">
</form>

这段代码可能会帮助您。单击按钮后,它会检查是否选择了文件,并相应地返回True/False。

<form method="post" enctype="multipart/form-data" onsubmit="return funccheck();"> 
Select image to upload:
 <input type="file" name="fileToUpload" id="fileToUpload"> 
<input class='new_post' type="submit" value="Upload Image" name="submit"> </form>
<script>
 function funccheck() { 
var get_photo = $('#fileToUpload').get(0).files.length; 
// If 0 file show error 
if (get_photo == 0) { 
 openandclose('.error_box' , 'emptyyyy.', 1700); 
 $('.error_box').focus();
 return false; //stops page loading
 }
return true; // initiates page loading
});
</script>

试试这个:

$('.new_post').click(function(e) { var get_photo = $('#fileToUpload').get(0).files.length; // If 0 file show error if (get_photo == 0) { openandclose('.error_box' , 'emptyyyy.', 1700); $('.error_box').focus(); e.preventDefault(); return false; } });

变量e是事件,如果没有文件,函数preventDefault将阻止表单提交。