2017-01-09 24 views
1

jqueryに入力しようとしていますが、入力フィールドに値がある場合 これらのコードを試しましたが、動作しません。jskeryはnullではありません。

私に教えてください!

if ($('#user-email').val() != ''){ 
    $(".email-capt").css({"position":"absolute","margin-top":"0px"}); 
} 
<div class="input-container input-email"> 
    <button class="btn btn-default email-btn"><span class="glyphicon glyphicon-chevron-right"></span></button> 
    <input type="email" required="" value="" tabindex="1" name="name" class="" id="user-email"> 
    <label for="arrival" class="email-capt">Enter your email to be in the know</label> 
</div> 
+3

私たちにあなたのHTMLを表示してください – urbz

+0

このコードはボタンクリックで動作していますか?あなたは何を得ているのですか? – Samir

答えて

1

あなたのinputフィールドの値が変更されたときにチェックする必要があります。現時点では、DOMがロードされた時点を確認しています。

代わりに、これを試してみてください:

$(".email-btn").click(function(){ // if button is clicked 
    if($.trim($(this).val()) != ''){ 
     $(".email-capt").css({"position":"absolute", "margin-top":"0px"}); 
    } 
}); 
1

function checkFilled() { 
 
    var inputVal = document.getElementById("subEmail"); 
 
    if (inputVal.value == "") { 
 
     inputVal.style.backgroundColor = "yellow"; 
 
    } 
 
    else{ 
 
     inputVal.style.backgroundColor = "green"; 
 
    } 
 
} 
 

 
checkFilled();
<input type="text" id="subEmail" onchange="checkFilled();">

0
:あなたは、あなたがこのような何かを行うことができます buttonをクリックしたときにチェックしたい場合は

$("#user-email").change(function(){ // on input value change 
    if($.trim($(this).val()) != ''){ 
     $(".email-capt").css({"position":"absolute", "margin-top":"0px"}); 
    } 
}); 

$('button').click(function() { 
 
    if ($('#user-email').val() != ''){ 
 
    $(".email-capt").css({"display":"block","color":"red"}); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<div class="input-container input-email"> 
 
    <button class="btn btn-default email-btn">Click</button> 
 
    <input type="email" required tabindex="1" name="name" id="user-email"> 
 
    <label for="arrival" class="email-capt" style="display:none;">Enter your email to be in the know</label> 
 
</div>

問題は、ページがロードされるときにjsコードが1回だけ実行されることでした。
コードを実行するボタンのonClickを定義する必要があります。そのためには - $('button').click(function() {...});

関連する問題