Home > Mobile >  JavaScript Input not allowing decimals
JavaScript Input not allowing decimals

Time:09-28

I have this setting on my page to set an input automatically to 0 if the input is empty. However, the input does not allow me to enter [or recognise] a decimal/dot. Any ideas why this is happening and how to get around this?

const updateSettings = (e) => {
        if(e.target.value === '') {
            e.target.value = 0;
        } else {
            e.target.value -= 0;
        }
        dispatch({
            type: 'UPDATE_SETTINGS',
            setting: e.target.name,
            value: e.target.type === 'checkbox' ? e.target.checked : e.target.value
        })

<input type="text" id="amount" name="amount" value={settings.amount} onChange={(e) => updateSettings(e)} />

Much appreciated, thanks!

CodePudding user response:

The issue is, when target.value is not empty, you try to minus 0 from it. When the value you enter is a . this isn't recognise as a valid operation as you're trying to minus a string that can't be parsed to a number (.) and a number (0-9).

I'm not sure why you need to minus 0 from target.value. Either way, if you get rid of your else block it should work.

edit - based on comment

I'm not sure of your exact use case, but there's a few ways you can handle the input field having a zero by default, and let the user replace it with their own value/s. You can use setState and pass that state to the value attribute, or you can use defaultValue={0}. Either one will allow the user to update the field normally.

Alternatively, you can set the type attribute to number and this will handle 0-9 and . as per your requirements.

What you can't have though is, making the input to always set to 0 when the input is empty (as in your if block), and not have a 0 at the start, given that the user won't be able to delete it.

CodePudding user response:

Thanks to @Kerron for his feedback, this is the solution that works:

  if(e.target.value.charAt(0) == '0' && e.target.value > 0) {
       e.target.value = e.target.value.substring(1) 
    }
  • Related