Подтвердить что ты не робот

JQuery проверяет, имеет ли какой-либо ввод текста значение

Я хочу спросить, есть ли лучший способ в jQuery выбрать несколько ввода текста, а затем проверить, имеет ли какое-либо из них значение. Здесь мой код:

if ($("#reference").val() != "" || $("#pin").val() != "" || $("#fName").val() != "" || $("#mName").val() != "" || $("#datepicker").val() != "") { /*logic goes here */ }
4b9b3361

Ответ 1

Вы можете сделать следующее:

if ($("#reference,#pin,#fName,#mName,#datepicker").filter(function() { return $(this).val(); }).length > 0) {
  //..
}

Использование общей функции, подобной следующей, сделает ее многоразовой:

function hasValue(elem) {
    return $(elem).filter(function() { return $(this).val(); }).length > 0;
}

И вы можете назвать это следующим образом:

hasValue("#my-input-id");

Ответ 2

Попробуйте jQuery each()

 $('input[type=text]').each(function(){
     var text_value=$(this).val();
     if(text_value!='')
       {
        console.log('Value exist');
        }

   })

Ответ 3

Просто используйте это:

if (!$("#id").val().length == 0))

Ответ 4

Проблема с получением свойства length на filter() заключается в том, что jQuery будет оценивать каждый отдельный элемент в коллекции, просто чтобы заполнить счет, когда все, о чем мы заботимся, - это значение больше нуля.

Ни один из текущих ответов и даже jQuery собственный .is(), .has() и .filter() использовать короткое замыкание, как только будут выполнены критерии.

Вы можете определить простой метод расширения, называемый .any() следующим образом:

jQuery.fn.any = function(filter){ 
    for (i=0 ; i<this.length ; i++) {
     if (filter.call(this[i])) return true;
  }
  return false;
};

И затем передайте функцию фильтрации следующим образом:

var someInputsEmpty = $("#reference,#pin,#fName,#mName,#datepicker").any(function() { 
    return this.value == '';
});

jQuery.fn.any = function(filter){ 
	for (i=0 ; i<this.length ; i++) {
  	 if (filter.call(this[i])) return true;
  }
  return false;
};

$(function() {
	
  var gotMatch = $(":input").any(function() { 
                   return this.value == 'hi';
                 });

  if (gotMatch) {
    console.log("Hello to you too!");
  } else {
  	console.log("Why don't you say Hi!");
  }
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" value="">
<input type="text" value="">
<input type="text" value="">

Ответ 5

Как насчет:

http://jsfiddle.net/lollero/rr2ss/1/

Другой пример: http://jsfiddle.net/lollero/rr2ss/12/

$(function() {

    // Check value of each and every input element....
    // Which you can of course change to be more specific, like: $('#myForm input')
    $( "input" ).val(function( i, val ) {

        // Return the console log IF value is not empty
        // value=" " still counts as "not empty", because technically it isn't
        // You could of course replace the console.log(); with anything you'd like
        val && console.log('not empty: input-' + (++i) );

        // Note that you don't have to return val if you don't  want to, it just for show in this case.
        return val

    });

});