2013-09-29 125 views
0

我有一个表单,它有2个按钮:'提交'和'保存'。提交表单后,根据按钮按下两种单独的功能运行。我想要做的是在按下提交按钮时调用一个函数来检查空字段。我的代码在函数内调用javascript函数

部分:

function valuecheck(){ 
    var msg=""; 
    if($F('entrepreneur_name')==""){ 

    msg+="You need to fill the product name field!\n"; 
    document.getElementById("entrepreneur_name").focus(); 
    } 

    if($F('address')==""){ 
     msg+="You need to fill in address!\n"; 

    } 
     if (msg) 
    {alert(msg); 
    return false; 
    } 
    } 

<?php 
$chkbutton=$_POST['submit']; 
switch ($chkbutton) 
{ 

case "Submit": 
// how to call the JavaScript function here.. 
...//rest of the code 
?> 

形式:

<input type="submit" style="width:10%" name="submit" value="Save" > 
<input type="submit" style="width:10%" name="submit" value="Submit" > 

如何调用机箱内的JavaScript函数 “提交”:

在此先感谢。

<form name='myform' method='post' onSubmit="myFunction()"> 

而在你的js函数:

+5

您不会像这样调用PHP的JavaScript函数,您在**提交表单之前检查字段是否为空**。 – adeneo

回答

0
<input type="submit" style="width:10%" name="submit" value="Submit" onclick="Validate()" > 

<script> 
function Validate() 
{ 
// your validation 
} 
</script> 
0

您可以在表单级别之前提交为此

function myFunction() 
{ 
    if(!...) 
    return false; //don't submit the form 
} 
0

有很多方法从PHP函数调用JavaScript函数..

echo '<script type="text/javascript">' 
, 'yourJSFunction();' 
, '</script>'; 

或者你也可以做到这一点的方式...

<?php 
// some php stuff 
?> 
<script type="text/javascript"> 
    yourJSFunction(); 
</script> 

希望它可以帮助...

0

的替代sskoko的回答是:

var submitButton = document.getElementById('submit-button'); 
submitButton.addEventListener('click', function(event) { 
    valuecheck(); 
}, false); 

虽然我有偷偷摸摸地认为,当你的值无效时,你需要使用event.preventDefault()来阻止表单提交。

该方法可以要么在传递给addEventListener()匿名函数被调用,或event可能需要传递到valuecheck()然后preventDefault()可称为那里。玩弄它,看看。