1

I am trying to apply these css in jquery when the input field have some value, I tried these jquery codes, but it's not working.

Please suggest me!

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>
2
  • 3
    Show us your HTML Commented Jan 9, 2017 at 7:53
  • Is this piece of code is working on button click? What is the error you are getting? Commented Jan 9, 2017 at 8:55

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

You need to check when your input field's value is changing. At the moment, you are checking when the DOM loads.

Try this out, instead:

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

If you want to check when the button is clicked, you can do something like this:

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

Comments

0

$('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>

The problem was that, the js code only runs one time when the page is loaded.
You need to define that onClick of the button the code should run. For that use this -- $('button').click(function() {...});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.