Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a form which has 2 buttons: 'Submit' and 'Save'. Upon the submission of the form two kind of separate function run, depending on the button pressed. What I want to do is to call a function to check for empty fields when submit button is pressed.

Part of my code:

    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
 ?>

the form:

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

how to call the javascript function inside the case "Submit":

Thanks in advance.

share|improve this question
5  
You don't call a javascript function from PHP like that, you check if the fields are empty before submitting the form. –  adeneo Sep 29 at 6:09
add comment

4 Answers

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

and

<script>
function Validate()
{
// your validation
}
</script>
share|improve this answer
add comment

You can do this on the form level prior submission:

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

And in your js function:

function myFunction()
{
  if( !...)
    return false; //don't submit the form
}
share|improve this answer
add comment

There are many ways to call JavaScript function from php function..

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

Or you can do this way...

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

Hope it helps...

share|improve this answer
add comment

An alternative to sskoko's answer:

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

Though I have a sneaking suspicion that you will need to use event.preventDefault() to keep the form from submitting, when your values are invalid.

The method may have to be called either in the anonymous function passed to addEventListener(), or event may need to be passed into valuecheck() and then preventDefault() could be called down there. Play around with it and see.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.