Reputation: 201
My question is what Javascript function for to make the button only appears when the user start inputting to the textbox, if its not the button will not appear.
Here's my code
<label for="color" class="control-label col-xs-4">
<p class="left">Color/s</p>
</label>
<div class="col-xs-7">
<input name="color" class="form-control req" autocomplete = "off" />
<input type="button" value="Add Color" />
</div>
Upvotes: 1
Views: 82
Reputation: 5419
Hide your button (via style)
<label for="color" class="control-label col-xs-4"><p class="left">Color/s</p></label>
<div class="col-xs-7">
<input name="color" class="form-control req" autocomplete = "off" />
<input type="button" value="Add Color" style="display:none" />
add JS like this
$( ".form-control" ).keypress(function() {
$(this).next().show();
$(this).unbind('keypress');
});
Upvotes: 4
Reputation: 14423
All you got to do is add an input
listener and check if the input is empty or not.
var button = $('input[type=button]');
button.hide();
//hide it at the beginning.
$('input[name=color]').on('input', function() {
//If input changes
if ($(this).val().length > 0) {
//If it's not empty show it
button.show();
} else {
//If it's empty hide it
button.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="color" class="control-label col-xs-4">
<p class="left">Color/s</p>
</label>
<div class="col-xs-7">
<input name="color" class="form-control req" autocomplete="off" />
<input type="button" value="Add Color" />
Upvotes: 2
Reputation: 207511
Using just CSS, you can show and hide the button with the required attribute.
input[name="color"]:valid + input[type="button"] {
display: inline;
}
input[name="color"]:invalid + input[type="button"] {
display: none;
}
<label for="color" class="control-label col-xs-4">
<p class="left">Color/s</p>
</label>
<div class="col-xs-7">
<input name="color" class="form-control req" autocomplete="off" required/>
<input type="button" value="Add Color" />
</div>
Upvotes: 4
Reputation: 67207
Try to use the input
event,
$('input[name="color"]').on('input',function(){
$('input[type="button"]')[0].disabled = (this.value.trim().length == 0);
}).trigger('input');
Upvotes: 5