填充两个输入时更改图像

时间:2016-04-28 10:31:34

标签: jquery css input

我有两个输入和一个图像......当两个输入都被填满时,是否可以更改图像?

HTML:

<div class="loginForm">
    <input class="input jmeno" type="text" name="jmeno" placeholder="jmeno" value=""><br>
    <div id="input_container"><input class="input heslo" type="text" name="heslo" placeholder="heslo" value="">
        <img src="https://www.w3.org/2005/ajar/icons/16dot-blue.gif" id="input-blue-img">
        <img src="http://www.berrylocate.com/images/dotgreen.png" id="input-green-img">
    </div>  
</div>

CSS:

#input-green-img {display:none;}

JS:

var $allInputs = $("input:text"),
$button = $("#input-blue-img");
$button2 = $("#input-green-img");
$allInputs.change(function() {
    var isEmpty = $allInputs.filter(function() {
        return ($(this).val()=="");
    });
    $button.hide();
    $button2.show();
    if(isEmpty.length == 0) {
        $button.show();
    }
});

JSfiddle:https://jsfiddle.net/qeubzwvy/1/

1 个答案:

答案 0 :(得分:3)

是的,试试这种方式

首先使用keyup事件立即捕获输入的更改,然后检查两者是否都有值,并显示/隐藏右键:

$('input').on('keyup',function(){
    var complete = true;
    $allInputs.each(function(){
       if($(this).val() === "") complete = false;
   });

   if(complete){
       $button.hide();
       $button2.show();
   } else {
       $button.show();
       $button2.hide();
   }
});

请在此处查看示例:https://jsfiddle.net/qeubzwvy/6/

或在纯JavaScript中,如果您愿意:

var allInputs = document.getElementsByTagName("input"),
    button1 = document.getElementById('input-blue-img'),
    button2 = document.getElementById('input-green-img');

for(i=0; i<allInputs.length; i++) {
    allInputs[i].onkeyup=function(){
    var completed = true;
    for(y=0; y<allInputs.length; y++) {
        if(allInputs[y].value.length === 0) completed = false;
    }
    if(completed){
        button1.style.display = 'none';
      button2.style.display = 'block';
    } else {
        button1.style.display = 'block';
      button2.style.display = 'none';
    }
  };
}

FIDDLE