-1

Hi I am just curious why the onsubmit function won't respond if the validation function is enclosed inside: (function(){ })();

<form id="testform" name="entform" onsubmit="return promptChar()" method="post">
 <input id="input-text" name="entchar" type="text" placeholder="Enter Text" />
 <input type="submit" value="Send" />
</form>

<script>
 (function(){

  function promptChar(){
  var field = document.getElementById('input-text').value;

   if(field == "a"){
    alert('hey');
    return false
   }
  }
 })();
</script>

https://jsfiddle.net/aqqn5u5v/

please also try to test it locally and copy the code

chrislash
  • 1
  • 2

1 Answers1

0

Inline event listeners expects handler function to be under global-scope but in your script, handler is in the local scope of IIFE

(function(){})();(IIFE), executes immediately after it’s created.[Ref]

function promptChar() {
  var field = document.getElementById('input-text').value;
  if (field == "a") {
    alert('hey');
    return false
  }
}
<form id="testform" name="entform" onsubmit="return promptChar()" method="post">
  <input id="input-text" name="entchar" type="text" placeholder="Enter Text" />
  <input type="submit" value="Send" />
</form>

Updated Fiddle

Community
  • 1
  • 1
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • hi thanks for the response. I don't understand it much. I am basically new to javascript, when do I need to use (function(){})(); ? and, is it safe to use it? – chrislash Jun 14 '16 at 18:02