简体   繁体   中英

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?

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

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

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

function validateAddress() {
  return $('.checkMe[value!=""]').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) { 

您是否在检查元素的ID时添加#,换句话说,生成的文本是这样的:

$('#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM