Javascript not working somehow - not sure what I am doing wrong :/

93 Views Asked by At

I am not sure what is wrong so I just thought of asking you all. I want to validate some variables via JS before I send them to my PHP Script, but somehow it's not working as I want and I am not sure why. Here my example code :

HTML

<script src="jadd.js" type="text/javascript"></script>
<form name="jadd" action="./func/add_job.php" method="post" onsubmit="return vf()">
<a href="javascript:document.jadd.submit()">random submit</a>
...
<input type="text" size="100" maxlength="150" name="jt" />
...
</form>

Javascript (jadd.js):

function vf() {
var x=document.forms["jadd"]["jt"].value;
  if (x==null || x=="") {
    alert("Field must be filled out");
    return false;
  }
}
3

There are 3 best solutions below

2
On

Try using vf_addjob() instead of vf()

should be :

onsubmit="return vf_addjob()"
1
On

You have two problemsedited your question.

  1. When you programatically submit a form, you won't trigger the submit event. Use a real submit button (<input type="submit">), not a link with JavaScript instead of an HTTP URI. (You can use CSS to make a button look like a link if you really want to).
  2. You are trying to call a function called vf but you have defined a function called vf_addjob, you need to use the same name!
0
On
  1. Remove your a href... button.
  2. Add inside the form this <input type="submit" value="click me">

Should look like this:

<script src="jadd.js" type="text/javascript"></script>
<form name="jadd" action="./func/add_job.php" method="post" onsubmit="return vf()">
...
<input type="text" size="100" maxlength="150" name="jt" />
...
<input type="submit" value="click me">
</form>

It would also be good practice to add a return true; in the JS function. But that's more for code readability.