Javascript – How to call function inside jQuery code

Review a Javascript code snippet to call a function which declared inside jQuery code :


<script>
   //javascript
  function submitSearchForm() {

	updateErrorMessage("Please enter a website url");
		
  }

  //jquery
  jQuery(document).ready(function($) {

	function updateErrorMessage(msg) {
		$('#error').html(msg).hide().fadeIn(500);
	}

     }
  );
</script>

But, browser console shows the updateErrorMessage function is not defined.


   Uncaught ReferenceError: updateErrorMessage is not defined

Solution

To call the function which is declared inside jQuery code, make it global access by adding the function to window object :


<script>
  function submitSearchForm() {

	updateErrorMessage("Please enter a website url");
		
  }

  jQuery(document).ready(function($) {

	//make it global access
	window.updateErrorMessage = function(msg) {
		$('#error').html(msg).hide().fadeIn(500);
	}

     }
  );
</script>

6 comments on “Javascript – How to call function inside jQuery code

  1. Ummmm – I don’t think so… The function is called submitSearchForm… you never call it

    Reply
  2. what if the javascript is in another file and not in the same file in which jquery code is written

    Reply
  3. But you would want the function to have something like this

    function myFunction ()
    {
    $(‘.selection’).css({display:none});
    }

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *