Priyanka Pachori Priyanka Pachori - 4 months ago 10
jQuery Question

How to append % symbol in input type=text on user input?

I am using a number spinner, and I want the input to have % symbol in the text box, by default. I tried using %, but it adds the symbol outside the box. This is the link for reference-
http://codepen.io/Thomas-Lebeau/pen/csHqx

This is my code:

<div id=spinner class="container">
<div class="input-group spinner">
<input type="text" class="form-control" value="0">
<div class="input-group-btn-vertical">
<button class="btn btn-default" type="button"><i class="fa fa-caret-up" style="color: #C41C01"></i></button>
<button class="btn btn-default" type="button"><i class="fa fa-caret-down" style="color: #20AD4E"></i></button>
</div>
</div>
</div>

/*
* number spinner
*/

(function ($) {
var minNumber = -100;
var maxNumber = 100;
$('.spinner .btn:first-of-type').on('click', function() {
if($('.spinner input').val() == maxNumber){
return false;
}else{
$('.spinner input').val( parseInt($('.spinner input').val(), 10) + 5 +'%');
}
});

$('.spinner .btn:last-of-type').on('click', function() {
if($('.spinner input').val() == minNumber){
return false;
}else{
$('.spinner input').val( parseInt($('.spinner input').val(), 10) -5+'%');
}
});
})(jQuery);

Answer

You can do it with jQuery change event. It will add '%' symbol at the end of your input.

(function($) {
  var minNumber = -100;
  var maxNumber = 100;
  $('.spinner .btn:first-of-type').on('click', function() {
    if ($('.spinner input').val() == maxNumber) {
      return false;
    } else {
      $('.spinner input').val(parseInt($('.spinner input').val(), 10) + 5 + '%');
    }
  });

  $('.txtinput').on("change", function() {
    var inputVal = parseFloat($(this).val().replace('%','')) || 0 ;
    $(this).val(inputVal + '%' );
  });

  $('.spinner .btn:last-of-type').on('click', function() {
    if ($('.spinner input').val() == minNumber) {
      return false;
    } else {
      $('.spinner input').val(parseInt($('.spinner input').val(), 10) - 5 + '%');
    }
  });
})(jQuery);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=spinner class="container">
  <div class="input-group spinner">
    <input type="text" class="form-control txtinput" value="0">
    <div class="input-group-btn-vertical">
      <button class="btn btn-default" type="button"><i class="fa fa-caret-up" style="color: #C41C01"></i>
      </button>
      <button class="btn btn-default" type="button"><i class="fa fa-caret-down" style="color: #20AD4E"></i>
      </button>
    </div>
  </div>
</div>