简体   繁体   中英

Calling JS function in another function

I am trying to call a function inside another function but its not working.

PS i am a beginnner in JS

<script type="text/javascript">
    <!--
    // Form validation code will come here.
    function validate() {
        madatorychk(name);
        //This functions makes sure that madatory fields are filled
        function madatorychk(fieldid) {
            var node = document.myForm.fieldid;
            if (node.value == "") {
                alert("This field cannot be left empty");
                document.myForm.fieldid.focus();
                return false;
            }

        }
    }
    //-->
</script> 

<form method="get" onsubmit="return(validate());"  name="myForm">
    <label>Name: <input type="text" id="name"></label> </form>
</form>

You need to use bracket notation to access object properties with variable name.

So document.myForm.fieldid (it tries to take a form element with the name literally fieldid ) is not correct and should be document.myForm[fieldid] :

function validate() {

    return madatorychk('name');

    //This functions makes sure that madatory fields are filled
    function madatorychk(fieldid) {
        var node = document.myForm[fieldid];
        if (node.value == "") {
            alert("This field cannot be left empty");
            document.myForm[fieldid].focus();
            return false;
        }
    }
}

For this also make sure you have named form element:

Name: <input type="text" name="name" />

And finally, very important is that you need to return result of madatorychk :

return madatorychk('name');

One more thing. You probably don't want to allow not only empty but also usernames with just spaces, so trim input before validation:

if (node.value.trim() == "") {
    alert("This field cannot be left empty");
    document.myForm[fieldid].focus();
    return false;
}

Demo: http://jsfiddle.net/747twprf/

You have a few errors:

  • you pass name (nothing) instead of "name"
  • you don't return from the internal function
  • you get the property called "fieldid" instead of the one whose name is in fieldid

Here's a fixed code:

function validate() {
     return madatorychk("name"); // note the return and the "name"
     function madatorychk (fieldid) {
        var node = document.myForm[fieldid]; // note the [fieldid]
        if (node.value == "" ) {
            alert("This field cannot be left empty");
            document.myForm[fieldid].focus() ;
            return false;
        }
     }
}

put function declaration outside of validate function.

 //This functions makes sure that madatory fields are filled
             function madatorychk (fieldid) {
               var node = document.myForm.fieldid;
               if (node.value == "" ) {
               alert("This field cannot be left empty");
               document.myForm.fieldid.focus() ;
               return false;
             }  


        function validate(){
          madatorychk(name);


        }

Well, the following works for me:

<script>
    // Form validation code will come here.
    function validate()
    {
        madatorychk(name);
        //This functions makes sure that madatory fields are filled
        function madatorychk (fieldid) {
            var node = document.querySelector('#name');
            if (node.value == "" ) {
                alert("This field cannot be left empty");
                node.focus();
                return false;
            }

        }
    }
</script>
<form method="get" name="myForm" onsubmit="return validate();">
    <label>Name: <input type="text" id="name"></label> </form>
</form>

I changed the value of the onsubmit attribute and document.myForm.fieldid was not a valid element path.

Example here .

Prior to JavaScript 1.2, function definition was allowed only in toplevel global code but JavaScript 1.2 allows function definitions to be nested within other functions as well.

Still there is a restriction that function definitions may not appear within loops or conditionals. These restrictions on function definitions apply only to function declarations with the function statement.

But still the best way to do this would be to define the functions separately and just call it inside the first function , since the second function is a pretty handy function and could be used elsewhere. Also use 'id' to recognize a form rather than using a name to do so. And passing the node itself as argument would help you use the same function for any node of any form :

//This functions makes sure that mandatory fields are filled
 function mandatoryChk(node) {
    if (node.value == "" ) {
      alert("This field cannot be left empty");
      node.focus();
      return false;
    }
    else
      return true;
 }
 function validate() {
    var Name =  document.getElementById("myForm").elements['name'];
    return mandatoryChk(Name);
 }

And use the following HTML:

<form method="get" onsubmit="validate();"  id="myForm">
    <label>Name: <input type="text" id="name" name="name"></label>
    <input type='submit' value='Submit'/>
</form>

List of changes done:

  • Changed the 'name' property of the form to 'id' property and added 'name' property to the text input. Use id to recognize forms and names to recognize inputs.
  • Included a submit button, without which most browsers do not submit forms.
  • Changed the function call in the 'onsubmit' event in the form. The 'onsubmit' event from an HTML form is not recommended though.
  • Separated mandatoryChk() and validate() functions for the sake of 'code-reuse'.
  • Renamed mandatorychk() to mandatoryChk() to suit the Coding Conventions (see: Coding Conventions )
  • The input node has been defined already in the validate function and this node is then passed to the mandatoryChk() function. This makes mandatoryChk() able to perform the checking on any text input of any form.
  • Added alternative return value for True cases, mandatoryChk().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM