0

see the js code first:

let javascript = {
checkValidations: function(){
    let firstName = document.getElementById("firstName");
    let lastName = document.getElementById("lastName");
    let age = document.getElementById("age");
    let flag = 0;
    if(firstName.value==null || firstName.value==""){
        document.getElementById("firstNameError").innerHTML = "First name cannot be blank"; 
        flag = 1;
    }
    if(lastName.value==null || lastName.value==""){
        document.getElementById("lastNameError").innerHTML = "Last name cannot be blank";   
        flag = 1;
    }
    if(Number.isNaN(age) || age==null || age=="" || Number(age)<18 || Number(age)>120){
        document.getElementById("ageError").innerHTML = "Age is not in required format";
        flag = 1;
    }
    if(flag==0){
        // save values
    }
};

And now I am trying to call this function from a button event:

<button class="btn btn-success" onclick="javascript.checkValidations">

Its not working ! I am doing this just to provide modularity to my code.

Can you tell me a way, how to achieve this ?

MoheeBoy
  • 1
  • 4
  • 1
    `javascript.checkValidations()` - but do try to not inline such a thing when you can use event listeners. And you do not reset the errors when the user fixes their errors – mplungjan Jul 12 '18 at 06:57
  • 1
    Instead of trying to write inline Javascript, it would be much more elegant to add event listeners properly instead – CertainPerformance Jul 12 '18 at 06:57
  • 1
    If you do `document.querySelector('.btn-success').onclick = javascript.checkValidations;` instead, it will work. –  Jul 12 '18 at 06:59

1 Answers1

0

checkValidations is a function. you need to call it using parenthesis.

<button class="btn btn-success" onclick="javascript.checkValidations()">
Code_maniac
  • 270
  • 1
  • 4
  • 16