IceDawg
IceDawg

Reputation: 327

jQuery field validation not working

I want to validate user input when the user clicked on the submit button, but it won't work.

jQuery

$(document).ready(function() {
   function validateForm() {
      if ($('#u').value() == '') 
      {
         alert("no value found");
         return false;
      }

  });

});

HTML

<form name="myForm" action="main.php" onsubmit="return validateForm()" method="post">
   <input type="text" id="u" />
   <input type="submit" value="submit" />
</form>

Upvotes: 1

Views: 62

Answers (4)

Aldi Unanto
Aldi Unanto

Reputation: 3682

By the way, I found an awkwardness in your code. Let's focus to this line :

  ......
   if ($('#u').value() == '') 
   {
     alert("no value found");
     return false;
   }

});

});

There's two });, which one for $(document) and which one for if() ?? Although for if(), don't type like that, just } for conditional closing. And for make a function ..., you don't need to put function inside $(document).ready. It can stand-alone. For example :

function validateForm() {

   if ($('#u').val() == '') 
   {
      alert("no value found");
      return false;
   }

}

And you should change .value() to .val()

See this for the result. Hope this helps

Upvotes: 0

Nick
Nick

Reputation: 1

As @Barmar suggested check your existing code for the missing id. I would add the id="u" to the <input type="text"> and also be careful in choosing id names that are ambiguous especially so that others could read your code later.

Now that you've edited the original question it is hard to see how my answer appears relevant

Upvotes: 0

Adil
Adil

Reputation: 148110

There are many problems in your code.

  • The value is not a function but attribute remove you can use val() and also you can not use value with jQuery object you can use it with DOM object.

  • You have probably forgot to assign id to your input field also assign that.

  • The statement <input type="text"> should b4 <input id="u" type="text">

  • You have extra parenthesis after closes currly bracket of function validateForm, you are not closing input tags.

Live Demo

if ($('#u').val() == '') 
{
   alert("no value found");
   return false;
}

You can use native javascript method getElementById to get the DOM element (object) and use value property of that object.

Live Demo

if (document.getElementById('u').value == '') 
{
     alert("no value found");
     return false;
}

Upvotes: 2

federicot
federicot

Reputation: 12331

Try

if ($('#u').value() == '') 
{
    alert("no value found");
    return false;
} else {
    $('form[name="myForm"]').submit();
}

Upvotes: 0

Related Questions