'Add active class to button when start typing in input
I have this code and I want to add the active class to the (withdraw-btn) button when I start typing in input and remove it again if I removed the text that I entered in input (when input is empty).
The code is running fine, but the problem is: that the active class is not added when I start typing in input so I must click outside that input.
I want to add an active class just start typing and remove it just delete the text in the input.
** Sorry For the bad language
HTML
<div class="row">
<div class="col-12 col-md-6">
<div class="withdrawal-amount">
<p>Withdrawal Amount (Minimum required: $10)</p>
<input type="text" placeholder="$10" class="withdrawal-amount-input">
</div>
</div>
<div class="col-12 col-sm-6 col-md-3">
<div class="withdraw-btn-upper">
<a href="#" class="withdraw-btn">Withdraw</a>
</div>
</div>
</div>
Javascript
function addActiveclass() {
$(".withdrawal-amount-input").on("change", function(){
if($(this).val() == "")
$(".withdraw-btn").removeClass('active');
else
$(".withdraw-btn").addClass('active');
});
}
addActiveclass();
Solution 1:[1]
Listen for the input event instead:
function addActiveclass() {
$(".withdrawal-amount-input").on("input", function(){
if($(this).val() == "")
$(".withdraw-btn").removeClass('active');
else
$(".withdraw-btn").addClass('active');
});
}
addActiveclass();
.active{
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-12 col-md-6">
<div class="withdrawal-amount">
<p>Withdrawal Amount (Minimum required: $10)</p>
<input type="text" placeholder="$10" class="withdrawal-amount-input">
</div>
</div>
<div class="col-12 col-sm-6 col-md-3">
<div class="withdraw-btn-upper">
<a href="#" class="withdraw-btn">Withdraw</a>
</div>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Spectric |
