1

I want to set an input field a user can type into with a £ sign fixed into that field. The user should not be able to delete or change this sign, but the user should be able to modify what comes after.

e.g.

  1. initial £
  2. user adds 10, result: £10
  3. user modified changes 10 -> 5000, result: £5000
  4. user deletes everything in the field, result: £ remains

The placeholder tag does not work as this is not visible when entering something in the field. The default value is also not doing quite what I want.

Place your stake: <input type="text" onChange={this.handleStakeChange}/>
mlunoe
  • 4,422
  • 4
  • 32
  • 43
The worm
  • 5,580
  • 14
  • 36
  • 49

3 Answers3

3

You can do so easily with CSS, and a background image:

.pounds-input {
  padding: 0 0 0 20px;
  background: url(https://cdn1.iconfinder.com/data/icons/business-finance-1-1/128/currency-sign-pound-128.png) no-repeat;
  background-size: 12px 12px;
  background-position: 2px 2px;
}
<input class="pounds-input" type="number" />
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

You can do this by simply placing an element with the symbol next to the input field and setting padding-left (or text-indent) on the input field itself:

.currency {
  position: relative;
  left: 15px;
}
input {
  padding-left: 12px;
  /* or text-indent: 12px; */
}
<label>Place your stake:</label>
<span class="currency">£</span>
<input type="number" />
mlunoe
  • 4,422
  • 4
  • 32
  • 43
0

You can avoid styles and just do plain React. Input values should come from state and change should give a new state. It's the concept of "controlled components"

https://facebook.github.io/react/docs/forms.html#controlled-components

In this way you have full control on what goes and comes from input elements. The state is the source of truth.

var StakeInput = React.createClass( {
getInitialState: function(){
  return {stake: ''}
},
handleStakeChange: function(e){
  const stakeInputValue = e.target.value.replace(/£/g, '').trim()
  this.setState({
    stake: stakeInputValue
  });
},
render: function(){
  return (
    <div>
    Place your stake: 
      <input type="text" value={'£ ' + this.state.stake}
        onChange={this.handleStakeChange}/>
    </div>
  )

    }
});
React.render(<StakeInput />, document.getElementById('output'));

http://jsbin.com/jemasub/edit?html,js,output

Giorgio Bozio
  • 2,982
  • 3
  • 20
  • 20