0

In my form I have the following

<script>
function validate(form)
{
   if(form.xyz.value=='') return false;
   return true;
}
</script>

<form onsubmit="return validate(this)">
  <input name="xyz">
  <input type="submit" value="submit">
</form>

For some reason I have to assign my onsubmit listener dynamically.

I cound define

document.forms[0].addEventListener('submit',validate);

But how to dynamically achieve return validate(this)

(I need pure JavaScript, not jQuery)

sbrbot
  • 6,169
  • 6
  • 43
  • 74
  • 1
    It's probably not related to your issue, but you should still fix the curly quotes in `onsubmit=”return validate(this)”`. On second thought, yeah, it's probably your problem. Testing your code in a jsFiddle shows that it works fine without the event listener. – j08691 Jun 18 '19 at 14:32
  • `For some reason I have to assign my onsubmit listener dynamically.` What is the reason? – Rohit.007 Jun 18 '19 at 14:41
  • The reason is that my form is created by ExtJS dinamically, then I come after it and want to assign validator on this form that is created previously. – sbrbot Jun 19 '19 at 06:14

2 Answers2

1

The first argument passed to the event handler function is the Event object. If you want to pass a different value, then create a new function and pass it explicitly.

function validateEventHandler(event) {
    return validate(this);
}

document.forms[0].addEventListener('submit',validateEventHandler);

… but I'd rewrite validate so that it just used this and not the form argument.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

According to answer on this post JavaScript code to stop form submission I implemented event.preventDeafault() command to prevent submission if the field is empty.

<form>
  <input name="xyz">
  <input type="submit" value="submit">
</form>

<script>
function validate(event)
{
  if(document.forms[0].xyz.value=='')
  { 
    alert('Mandatory field!');
    event.preventDefault();
  }
}
document.forms[0].addEventListener('submit',validate);
</script>
sbrbot
  • 6,169
  • 6
  • 43
  • 74
  • There's even an article about `preventDefault()` on W3Schools: https://www.w3schools.com/jsref/event_preventdefault.asp – sbrbot Jun 19 '19 at 06:40