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

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?

,

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 $('.checkMevalue!=""').length > 0;
}

,

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;
}

,

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) { 

,

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

$('#IDOfElement').val()

,

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;
}

Leave a Comment