Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Simple Form validation question

I am trying to write a very simple form validation, here is a sample snippet of what I have that works,

if($('input[name=name]').val() == ""){
    e.preventDefault();
    alert('prevented')
}

With that one rule in the if statement it is working. What I would like to do, is add a few more rules in that if statement such as

input[name=email]
input[name=company]

But something like this doesn't work

if($('input[name=name]').val() && $('input[name=email]').val() && $('input[name=company]').val() == "")

Is there a way to add those three rules in there? It doesn't seem to work with just the &&.

1 Answer

It seems like you are using jquery library for this and not core javascript. When using jquery selectors for input you will need to use : before input.

http://api.jquery.com/input-selector/

$(document).ready(function() {
      $( ":input") // selecting all inputs.
});

I would suggest to try console for any errors if any shows up.

I am not very familiar with this syntax, so I don't know about this.

if($('input[name=name]').val() && $('input[name=email]').val() && $('input[name=company]').val() == "")

Here is something I am familiar with

$(document).ready(function() {
    var name = $('#name').val(); 
    var email = $('#email').val();
    var company = $('#company').val();

if ( name == ' ' && email == ' ' && company == ' ') {
      e.preventDefault();
      alert("Prevent");
}
});

Good luck with your javaScript.