Vista
Vista

Reputation: 201

Button only appears when you start inputting

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

Answers (5)

Kar Reddy
Kar Reddy

Reputation: 168

Use onkeyup function to activate the button

Upvotes: 0

Dmytro Pastovenskyi
Dmytro Pastovenskyi

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

MinusFour
MinusFour

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

epascarello
epascarello

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

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

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');

DEMO

Upvotes: 5

Related Questions