Home > OS >  How to append prefix and suffix to input value Jquery
How to append prefix and suffix to input value Jquery

Time:11-16

I want to append prefix and suffix to a input value. for example my prefix is ABC and my suffix is DEF, now when an user type something to input then I want to append ABC-USERVAL-DEF that is (Prefix-user input-Suffix).Please help me out. I have tried something like this.

$("#input").on("keyup", function() {
  var prefix = 'ABC-'
  var suffix= '-DEF'
  var final = prefix   $(this).val()   suffix;
  $(this).val('');
  $(this).val(final);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id="input" val=''>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I have used @shrys code and enhance that code for backspace.

$("#input").on("keyup", function(e) {
  var prefix = 'ABC-';
  var suffix = '-DEF';
  var val = $(this).val().replace(prefix, '').replace(suffix, '');
  var final = prefix   val   suffix;
  $(this).val(final);
});

$("#input").on("keydown", function(e) {
  var key = event.keyCode || event.charCode;
  var prefix = 'ABC-';
  var suffix = '-DEF';
  if( key == 8 || key == 46 ){
    var val = $(this).val().replace(prefix, '').replace(suffix, '');
    $(this).val(val);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id="input" val=''>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

credits to @shrys

CodePudding user response:

I would like to thank @shrys for the answer and that solves my problems for now.

$("#input").on("keyup", function(e) {
  var prefix = 'ABC-';
  var suffix = '-DEF';
  var val = $(this).val().replace(prefix, '').replace(suffix, '');
  var final = prefix   val   suffix;
  $(this).val(final);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id="input" val=''>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

// I think there's a little bit of that with chang
$("#input").on("change", function (e) {
  let value = $(this).val();
  const prefix = 'ABC-';
  const suffix = '-DEF';
  value = value.replace(/(^ABC-)|(-DEF$)/g, '');
  $(this).val(prefix   value   suffix);
});
  • Related