Can I add a value before or after an input value?

I want to modify the text shown for the value, but without actually changing the value. So If I read out the value then it should still return 1000.

<input id="myInput" type="text" value="1000">

How can I add the text Foo before or Bar after 1000 withouth changing the value itself?

Foo and Bar should NOT be editable by the user.

5 Answers

1
Nimsrules On Best Solutions

var input = document.getElementById('myInput'); input.value = "Foo" + input.value + "Bar";

Edit

The markup

span {
   display: inline-block;
   position: relative;
}

span::after {
   content: 'mm';
   position: absolute;
   right: 5px;
   top: 0;
 }
<span>
   <input id="myInput" type="text" value="1000">
</span>

0
Alex On

This simplest way would be to and some elements before and after:

<span>foo</span>
<input id="myInput" type="text" value="1000">
<span>bar</span>

Then use CSS to style the <input />

1
prasanth On

Use data attribute for multiple input

$('.myInput').val(function(){
  var bef =$(this).attr('data-before');
  var aft =$(this).attr('data-after');
  return bef+$(this).val()+aft;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input class="myInput" type="text" data-before="foo" data-after="bar" value="1000">

<input class="myInput" type="text" data-before="foo1" data-after="bar1" value="1000">

<input class="myInput" type="text" data-before="foo2" data-after="bar2" value="1000">

2
Dacre Denny On

Though it's not the most elegant, one possibility would be to include the "Foo" and "Bar" parts of the string in the element's value attribute via a helper function (ie setValue() below), and then "sanitize" these extra parts out of the inputs value when accessing the desired value of the input (ie getValue() below):

/* Pad input value with foo bar via custom set helper function */
function setValue(value) {
  $('input').val('Foo' + value + 'Bar');
}

/* Extract real value from input value padded with foo bar via 
custom get helper function */
function getValue() {

  const lengthOfRealValue = $('input').val().length - 6;

  return $('input').val().substr(3, lengthOfRealValue);  
}

/* Set value and cause padded side effect */
setValue('hello-world');

/* Get value from padded input value */
console.log(getValue())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="myInput" type="text" value="1000">

1
Ahmed Elbendary On

can save value 1000 in data-value="1000"

and can select this value by document.querySelectorAll('[data-value]');

or

using

first input to display and second to post to server