如何在三个输入元素中有值时触发JavaScript函数

How to trigger a JavaScript function when there are values in three input elements?

本文关键字:函数 JavaScript 元素 输入 三个      更新时间:2023-09-26

当三个输入框上都有值时,如何触发事件?例如,我有三个输入元素:

<input type = "text" name = "item1" id = "item1" value="">
<input type = "text" name = "item2" id = "item2" value="">
<input type = "text" name = "item3" id = "item3" value="">

当这三个输入元素有一个值时,我想使用JavaScript输出一个结果,当它不满足条件时自动返回null。

<span> item1,item2,item3 has value </span>

EDIT1:

只有当3个输入框都有值时才显示结果,否则返回null。

EDIT2: 当3个输入框有值,我想设置一个复选框attr为真,否则false当它不是

使用onKeyUP事件,检查输入值是否为$(e).val().length>0

<标题>演示:

$('input[id^=item]').keyup(function(evt){
    var hasVal=Array.from($('input[id^=item]').filter((i,e)=>$(e).val().length>0)).map((e)=>$(e).attr('id')).join(',')
      
     $('span').html((hasVal.length)?hasVal+' has value':'No input has value')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "text" name = "item1" id = "item1" value="">
<input type = "text" name = "item2" id = "item2" value="">
<input type = "text" name = "item3" id = "item3" value="">
<br />
<span>  </span>

试试这个。如果你需要在第三个输入中显示,那么在第三个输入中使用onfocus而不是onchange。

<!DOCTYPE html>
<html>
 <head>
  <title>Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script>
   $(document).ready(function(){
     $('#showText').hide();
   });
   function canShowText(){
      if($('#item1').val().length>0 && $('#item2').val().length>0 && $('#item3').val().length>0)
    $('#showText').show();
   }
  </script>
 </head>
 <body>
  <input type="text" name="item1" id="item1" value="" onchange='canShowText()'><br>
  <input type="text" name="item2" id="item2" value="" onchange='canShowText()'><br>
  <input type="text" name="item3" id="item3" value="" onchange='canShowText()'><br>
  <span id='showText'> item1,item2,item3 has value </span>
 </body>
</html>

您可以使用.toArray(), .every(), input事件

function handleValues() {
  alert("all three inputs have value");
  span.html(arr.map(function(el) {return el.value}).join(","))
}
function handleInput(e) {
  arr.every(function(el) {
   return el.value.length;
  }) 
  ? handleValues() 
  : !!span.html("") && alert("all three inputs do not have value");
}
var input = $("input"), arr = input.toArray(), span = $("span");
input.on("input", handleInput);
handleInput();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "text" name = "item1" id = "item1" value="">
<input type = "text" name = "item2" id = "item2" value="">
<input type = "text" name = "item3" id = "item3" value=""><br>
<span></span>