2016-04-28 38 views
4

我有兩個輸入和一個圖像......當兩個輸入都填滿後,是否可以更改圖像?當兩個輸入都填滿時更改圖像

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/

+0

是你可以做的,只是同時檢查是否輸入是否爲空ňkeyup事件,並相應改變圖像的SRC – RRR

+0

查收https://jsfiddle.net/qeubzwvy/7/ – RRR

回答

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(); 
    } 
}); 

在這裏看到exampler: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

+0

作品:)非常感謝! –

+0

我可以再問一個問題嗎?如果我不能使用jQuery - 只有JS,我該如何改變這個腳本? –

+0

肯定安妮,你需要什麼 – pumpkinzzz

相關問題