Sprawdź czy wejścia są puste używając jQuery

Mam formularz, który chciałbym, aby wszystkie pola zostały wypełnione. Jeśli pole zostanie kliknięte, a następnie nie wypełnione, chciałbym wyświetlić czerwone tło.

Oto Mój kod:

$('#apply-form input').blur(function () {
  if ($('input:text').is(":empty")) {
    $(this).parents('p').addClass('warning');
  }
});

Stosuje klasę warning niezależnie od wypełnianego pola.

Co robię źle?
Author: Danil Speransky, 2009-12-06

16 answers

$('#apply-form input').blur(function()
{
    if( !$(this).val() ) {
          $(this).parents('p').addClass('warning');
    }
});

I niekoniecznie potrzebujesz .length lub sprawdź, czy jest to >0, ponieważ pusty łańcuch i tak ewaluuje na false, ale jeśli chcesz dla celów czytelności:

$('#apply-form input').blur(function()
{
    if( $(this).val().length === 0 ) {
        $(this).parents('p').addClass('warning');
    }
});

Jeśli jesteś pewien, że zawsze będzie działać na elemencie textfield, możesz po prostu użyć this.value.

$('#apply-form input').blur(function()
{
      if( !this.value ) {
            $(this).parents('p').addClass('warning');
      }
});

Należy również zauważyć, że $('input:text') chwyta wiele elementów, określa kontekst lub używa słowa kluczowego this, jeśli chcesz tylko odwołać się do pojedynczego elementu (pod warunkiem, że jest jedno pole tekstowe w kontekście Potomków/dzieci).

 671
Author: meder omuraliev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-09 18:42:51

Każdy ma rację pomysł, ale lubię być trochę bardziej wyraźne i przyciąć wartości.

$('#apply-form input').blur(function() {
     if(!$.trim(this.value).length) { // zero-length string AFTER a trim
            $(this).parents('p').addClass('warning');
     }
});

Jeśli nie używasz .długość, wtedy wpis ' 0 ' może zostać oznaczony jako zły, a wpis 5 spacji może zostać oznaczony jako ok bez $.trim . Powodzenia.

 140
Author: Alex Sexton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-12-06 06:51:18

Robienie tego na blur jest zbyt ograniczone. Zakłada, że nie było skupić się na polu formularza, więc wolę to zrobić na submit, i map przez wejście. Po latach radzenia sobie z fantazyjnym rozmyciem, skupieniem itp. sztuczki, utrzymanie rzeczy prostsze daje większą użyteczność tam, gdzie się liczy.

$('#signupform').submit(function() {
    var errors = 0;
    $("#signupform :input").map(function(){
         if( !$(this).val() ) {
              $(this).parents('td').addClass('warning');
              errors++;
        } else if ($(this).val()) {
              $(this).parents('td').removeClass('warning');
        }   
    });
    if(errors > 0){
        $('#errorwarn').text("All fields are required");
        return false;
    }
    // do the ajax..    
});
 30
Author: drewdeal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-21 19:21:53
if ($('input:text').val().length == 0) {
      $(this).parents('p').addClass('warning');
}
 18
Author: Graviton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-12-06 06:51:26

Możesz również użyć..

$('#apply-form input').blur(function()
{
    if( $(this).val() == '' ) {
          $(this).parents('p').addClass('warning');
    }
});

Jeśli masz wątpliwości co do spacji,spróbuj..

$('#apply-form input').blur(function()
{
    if( $(this).val().trim() == '' ) {
          $(this).parents('p').addClass('warning');
    }
});
 9
Author: Zigri2612,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-17 06:33:50

Dlaczego nikt nie wspomniał

$(this).filter('[value=]').addClass('warning');

Wydaje mi się bardziej podobne do jquery

 8
Author: Jamie Pate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-30 04:58:51

Rozważ użycie wtyczki jQuery validation zamiast tego. Może to być nieco przesada dla prostych pól wymaganych, ale jest na tyle dojrzały, że obsługuje przypadki krawędzi, o których jeszcze nie pomyślałeś(ani żaden z nas, dopóki na nie nie wpadliśmy).

Możesz oznaczyć wymagane pola klasą "required", uruchomić $('form').validate () w $(document).gotowe () i tyle wystarczy.

Jest nawet hostowany na Microsoft CDN zbyt, dla szybkiej dostawy: http://www.asp.net/ajaxlibrary/CDN.ashx

 4
Author: Dave Ward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-12-06 06:49:26

Zdarzenie keyup wykryje, czy użytkownik również wyczyścił pole (tzn. backspace podnosi zdarzenie, ale backspace nie podnosi zdarzenia Klawiatura W IE)

    $("#inputname").keyup(function() {

if (!this.value) {
    alert('The box is empty');
}});
 4
Author: Ouss Ama,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-29 17:24:42

Pseudo-selektor :empty jest używany, aby sprawdzić, czy element nie zawiera Potomków, należy sprawdzić wartość:

$('#apply-form input').blur(function() {
     if(!this.value) { // zero-length string
            $(this).parents('p').addClass('warning');
     }
});
 3
Author: CMS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-12-06 06:38:55

Jest jeszcze jedna rzecz, o której warto pomyśleć, obecnie może ona dodać klasę warning tylko wtedy, gdy jest pusta, co powiesz na ponowne usunięcie klasy, gdy Formularz nie jest już pusty.

Tak:

$('#apply-form input').blur(function()
{
    if( !$(this).val() ) {
          $(this).parents('p').addClass('warning');
    } else if ($(this).val()) {
          $(this).parents('p').removeClass('warning');
    }
});
 3
Author: xorinzor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-12 10:53:36

function checkForm() {
  return $('input[type=text]').filter(function () {
    return $(this).val().length === 0;
  }).length;
}
 3
Author: Vanilla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-25 04:54:00

Oto przykład użycia keyup dla wybranego wejścia. Używa również przycięcia, aby upewnić się, że sekwencja znaków zawierających tylko białe spacje nie wywołuje prawdziwej odpowiedzi. Jest to przykład, który może być użyty do rozpoczęcia pola wyszukiwania lub czegoś związanego z tego typu funkcjami.

YourObjNameSpace.yourJqueryInputElement.keyup(function (e){
   if($.trim($(this).val())){
       // trimmed value is truthy meaning real characters are entered
    }else{
       // trimmed value is falsey meaning empty input excluding just whitespace characters
    }
}
 2
Author: Frankie Loscavio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-30 18:51:54
$(function() {
  var fields = $('#search_form').serializeArray();
  is_blank = true;
  for (var i = 0; i < fields.length; i++) {
    // excluded fields
    if ((fields[i].name != "locale") && (fields[i].name != "utf8")) {
      if (fields[i].value) {
        is_blank = false;
      }
    }
  }
  if (is_blank) {
    $('#filters-button').append(': OFF');
  }
  else {
    $('#filters-button').append(': ON');
  }
});

Sprawdź, czy wszystkie pola są puste i dołącz do FILTRA_BUTTON

 2
Author: Mauro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-15 14:01:52

Możesz spróbować czegoś takiego:

$('#apply-form input[value!=""]').blur(function() {
    $(this).parents('p').addClass('warning');
});

Zastosuje Zdarzenie .blur() Tylko do wejść z pustymi wartościami.

 1
Author: Konstantin Kalbazov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-31 14:35:08
<script type="text/javascript">
$('input:text, input:password, textarea').blur(function()
    {
          var check = $(this).val();
          if(check == '')
          {
                $(this).parent().addClass('ym-error');
          }
          else
          {
                $(this).parent().removeClass('ym-error');  
          }
    });
 </script>// :)
 0
Author: Maher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-16 11:29:46

Z HTML 5 możemy użyć nowej funkcji "wymagane" wystarczy dodać go do tagu, który chcesz być wymagane jak:

<input type='text' required>

 0
Author: Atlantiz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-30 03:11:24