NibblyPig
NibblyPig

Reputation: 52942

Using JQuery, how do I check that at least one textbox is not empty?

Sounds simple but it's giving me grief:

Tried this:

function validateAddress() {

    if (!($('<%=txtPlaceName.ClientID%>').val() === "")
         || !($('<%=txtStreet.ClientID%>').val() === "")
         || !($('<%=txtAddress.ClientID%>').val() === "")
         || !($('<%=txtPostcode.ClientID%>').val() === "")) {

        return true;
    }

    return false;
}

and this:

function validateAddress() {

    if ($('<%=txtPlaceName.ClientID%>').val().length > 0
         || $('<%=txtStreet.ClientID%>').val().length > 0
         || $('<%=txtAddress.ClientID%>').val().length > 0
         || $('<%=txtPostcode.ClientID%>').val().length > 0) {

        return true;
    }

    return false;
}

but neither seem to work, am I doing it correctly?

Upvotes: 1

Views: 1574

Answers (5)

jsuggs
jsuggs

Reputation: 2652

I've been using classes to group functionality, so for your example give each of the element a class of address then your function would be:

function validateAddress() {
  $('.address').each(function() {
    if ($(this).val().length > 0) {
      return true;
    }
  }
  return false;
}

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630409

For a #ID selector you need a #, like this:

$('#<%=txtPlaceName.ClientID%>').val().length

But the quicker way could be to give them a class, e.g. CssClass="checkMe", then check those elements:

function validateAddress() {
  return $('.checkMe[value!=""]').length > 0;
}

Upvotes: 3

Anatoly G
Anatoly G

Reputation: 4152

are you adding # to the ID of the element when you check it, in other words, is the produced text like this:

$('#IDOfElement').val()

Upvotes: 0

Ken Browning
Ken Browning

Reputation: 29091

You're forgetting the hash mark to select something by id. Try:

function validateAddress() {

    if ($('#<%=txtPlaceName.ClientID%>').val().length > 0
         || $('#<%=txtStreet.ClientID%>').val().length > 0
         || $('#<%=txtAddress.ClientID%>').val().length > 0
         || $('#<%=txtPostcode.ClientID%>').val().length > 0) {

        return true;
    }

    return false;
}

Upvotes: 2

John Fisher
John Fisher

Reputation: 22719

It looks like you're missing the "#" in your jquery selectors for ids. Try this:

if ($('#<%=txtPlaceName.ClientID%>').val().length > 0 
     || $('#<%=txtStreet.ClientID%>').val().length > 0 
     || $('#<%=txtAddress.ClientID%>').val().length > 0 
     || $('#<%=txtPostcode.ClientID%>').val().length > 0) { 

Upvotes: 0

Related Questions