Help on input self value + literal text

forms
#1

<input name="inp_name" type="text" required="true" class="form-control" id="inp_id" dmx-bind:value="value ? (value + 'KGM') : null">

What I want to achieve:
input + literal text e.g: when I input 10 into above input I expect result 10KGM.

The problem:
the above code will result 10KGMKGMKGMKGMKGMKGM… (infinite KGM). I’ve tried with just value + 'KGM' but still get the same result.

Any help is much appreciated.

#2

Hello @transcoderm
Where is the value coming from?

#3

from the current input itself.

#4

When selecting the value I select the current form input value, thus no input name prefix like input_name.value.

#5

I see, @patrick can advise here better :slight_smile:

#6

try value ? (value.replace('KGM', '') + 'KGM') : null

1 Like
#7

@patrick kudos the above code does the trick except when user press backspace it will add another KGM. :thinking:

#8

How about value ? (value.replace(/\D/g, '') + 'KGM') : null, it will strip all non numeric characters. That way users can only enter numbers and KGM will always be added to the end.

Change the regexp when needed, for example if you want to allow number and the dot /[^0-9\.]/g.

1 Like
#9

Now that’s better. Thank you so much guys. I think that achieves what I need. Cheers!

#10

But for knowledge purpose, may I get to know why normal value + 'literal text' doesn’t work?

#11

The expression is triggered/executed each time some data/state on the page is updated/changed.

So the first time, user enters 10 in the input. '10' + 'KGM' = '10KGM' the input value becomes now 10KGM. Now something else on the triggers/executes the expression again, value is now '10KGM' + 'KGM' = '10KGMKGM'. So it adds an othe KGM to the previous value, this continues each time that the expression is triggered/executed.

2 Likes
#12

I see. I got it. Thank you again for the explanation. :+1:

unassigned patrick #13