Anish Ansari
Anish Ansari

Reputation: 179

How to append prefix and suffix to input value Jquery

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=''>

Upvotes: 0

Views: 1492

Answers (3)

vueAng
vueAng

Reputation: 453

// 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);
});

Upvotes: 0

Anish Ansari
Anish Ansari

Reputation: 179

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=''>

Upvotes: 0

Shashank Gb
Shashank Gb

Reputation: 1012

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=''>

credits to @shrys

Upvotes: 2

Related Questions