无法获取数字输入的值,如果输入大于0。

huangapple go评论70阅读模式
英文:

Can't get value of numeric input if input is greater then 0

问题

<input type="number" placeholder="人数*" class="user_number" min="1" max="5">
let user_number = document.getElementsByClassName("user_number");
if ($(user_number).val() > 0) {
    console.log($(user_number).val());
}
英文:
&lt;input type=&quot;number&quot; placeholder=&quot;Number of people*&quot; class=&quot;user_number&quot; min=&quot;1&quot; max=&quot;5&quot;&gt;
let user_number = document.getElementsByClassName(&quot;user_number&quot;);
if($(user_number).val() &gt; 0){
            console.log($(user_number).val());
        }

but when i put anything more than 0 console doesn't show up help please

答案1

得分: 1

你可以为"input"事件附加一个事件监听器,以便在每次值更改时进行检查。

$('.user_number').on('input', function() {
  if (this.valueAsNumber > 0) {
    console.log(this.value);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" placeholder="人数*" class="user_number" min="1" max="5">
英文:

You can attach an event listener for the "input" event so that the value is checked each time it changes.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

$(&#39;.user_number&#39;).on(&#39;input&#39;, function() {
  if (this.valueAsNumber &gt; 0) {
    console.log(this.value);
  }
});

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;input type=&quot;number&quot; placeholder=&quot;Number of people*&quot; class=&quot;user_number&quot; min=&quot;1&quot; max=&quot;5&quot;&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月14日 03:13:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定