views:

145

answers:

1

I have a form and I'm using jQuery to validate that the have entered in the correct information into the textboxs. That works fine, because I have this code:

var name = $("#business_name").val();
    if (name == "") {
        $('#namelabel').show()
        $("#business_name").focus();
        return false;
    }

that tests to see if it is null and will throw an error if it is not filled out. My problem is how to determine the nil value of a drop down menu of categories. I tried :

var category = $("#business_business_category_id").val();
    if (category == ""  || category == nil) {
        $('#categorylabel').show();
        $("#business_business_category_id").focus();
          return false;
    }

Which doesn't work. I'm assuming nil is not the correct syntax for jQuery or that I shouldn't be using .val but I couldn't find anything online about it.

+1  A: 

Unless the value for "nothing selected" is something else than an empty string or zero, you can make your code a lot simpler:

var category = $("#business_business_category_id").val();
    if (!category) {
        $('#categorylabel').show();
        $("#business_business_category_id").focus();
          return false;
    }

That will check for undefined, null, empty string or zero.

Another thing to note is that nil is not a javascript contant/keyword. You should use undefined (or null, but that's not the same, but that's another discussion)

Philippe Leybaert
I'm sure that's right. I tried it and it didn't work but found out it was setting the value to - Choose one -
Mike