繁体   English   中英

如果onsubmit在javascript中返回true,如何同时使用onsubmit进行验证和onclick进行任何操作

[英]How to use both onsubmit for validation and onclick for any operation if onsubmit return true in javascript

我已经在html中创建了表单,现在我尝试使用onsubmit进行验证,如果onsubmit返回true,则尝试使用onclick进行其他操作。 我找不到这样做的正确方法。

<form role="form" onsubmit='return formValidation()'>
        <div class="form-group">
          <p id="bookiderror" style="color: red"></p>
          <label >ಪುಸ್ತಕದ ಐಡಿ:</label>
          <input type="text" id="bookid" class="form-control">
        </div>
        <div class="form-group">
          <p id="booknameerror" style="color: red"></p>
          <label>ಪುಸ್ತಕದ ಹೆಸರು:</label>
          <input type="text" id="bookname" class="form-control">
        </div>
         <div class="form-group">
          <p id="rupeeserror" style="color: red"></p>
          <label >ರೂಪಾಯಿ:</label>
          <input type="text"id="rupees" class="form-control">
        </div>
         <div class="form-group">
          <p id="bookpubishererror" style="color: red"></p>
          <label >ಪುಸ್ತಕದ ಪ್ರಕಾಶಕರು:</label>
          <input type="text" id="bookpublisher" class="form-control">
        </div>
         <div class="form-group">
          <p id="bookeditionerror" style="color: red"></p>
          <label >ಪುಸ್ತಕದ ಆವೃತ್ತಿ:</label>
          <input type="text" id="bookedition" class="form-control">
        </div>
         <div class="form-group">
          <p id="bookyearerror" style="color: red"></p>
          <label >ಪುಸ್ತಕದ ವರ್ಷ:</label>
          <input type="text" id="bookyear" class="form-control">
        </div>
        <input type="submit" value="AddBook" class="btn btn-primary" onclick="addbook()" id="submit"/>
      </form>

您可以这样做。 formValidation方法应返回false,否则页面将刷新。

function formValidation(){
     //write your formValidation logic here
     if(form.isValid){
         //call your add book here
         addbook();
     }
     return false;
}
function formValidation(){


//Enter your validation logic here.
if (false) return false;

return true; //default

}

function addBook() {

if (formValidation()){
    //Your insertion code here.
}
else
{

    alert('Error message.'); 

}

}

现在,只需删除onClick函数,然后将addBook()函数放入onSubmit。

你不能

点击事件会先触发。 只有使用提交按钮的默认行为解决该问题后,才能激活并触发提交。

因此,无法在单击处理程序之前运行提交处理程序。

您需要:

  • 在每个单击处理程序的顶部执行提交处理程序所做的所有测试。
  • 让单击处理程序仅记录激活了哪个提交按钮,然后在提交处理程序结束时使用该按钮确定要执行的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM