jQuery: найти все элементы с - PullRequest
1 голос
/ 30 апреля 2020

Я ищу способ применить это решение ко всем полям, которые имеют <input type="number">.

До сих пор я видел только способ найти элемент по ID, используя jQuery, а затем прикрепите фильтр ввода. Однако я пытаюсь добавить такой фильтр к всем элементам с типом "цифра c".

Пример:

<html>
<body>
    <div>
        <input type="number">
    </div>                              
</body>
</html>

JS Функция:

// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        this.value = "";
      }
    });
  };
}(jQuery));

Применение модификатора к определенному элементу

$(document).ready(function() {
  $("#myTextBox").inputFilter(function(value) { // I need to find ALL elements with input type = number here instead of just myTextBox
    return /^\d*$/.test(value);    // Allow digits only, using a RegExp
  });
});

Обновление: Я попробовал следующее:

(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        this.value = "";
      }
    });
  };
}(jQuery));

if($('input[type="number"]').length > 0){
$('input[type="number"]').each(function(index, element){ console.log(element); // Successfully logs the element!
element.inputFilter(function(value) { // I need to find ALL elements with input type = number here instead of just myTextBox
    return /^\d*$/.test(value);    // Allow digits only, using a RegExp
  });

})
}

Получение ошибки: enter image description here

Ответы [ 2 ]

3 голосов
/ 30 апреля 2020

Используйте селектор атрибута:

$('input[type="number"]')...

Обрабатывайте результат как обычно, но имейте в виду, что inputFilter зарегистрирован как расширение jQuery и не определен для элементов DOM:

// Iterate over the matched elements. 'element' values are DOM elements and thus oblivious to jquery. For this reason you cannot call `inputFilter` on them.
$('input[type="number"]').each( function(index, element){ 
    console.log(element); // Successfully logs the element!
}

// Untested code (jQuery should handle the overhead of iterating over the elements.)
$('input[type="number"]').inputFilter(
   function(value) { // I need to find ALL elements with input type = number here instead of just myTextBox
      return /^\d*$/.test(value);    // Allow digits only, using a RegExp
   }
);
1 голос
/ 30 апреля 2020
if($('input[type="number"]').length > 0){
    //do something like as $('input[type="number"]').each(function(index, element){ console.log(element); })
}
...