Domanda

How I could create an <input type="text" /> with following restrictions for the User and formatting extensions, namely using JavaScript or jQuery?

  • The User can use only numeric chars. Nothing else.
  • The User can't delete the dot. Never. Is it possible? If it isn't and the user will remove the dot, how to give the dot back automatically on losing focus?
  • On blur (lose focus), if the decimal places are empty, script will fill it with zeros (↓).
  • I need this pattern for view: X XXX.XX (toFixed(2) I can use for two decimal places, but I don't know way to separate string according pattern).

Certainly you've noticed, that the text field should be the price. The script should operate on multiple input fields with class "pr-dec".

<input type="text" class="pr-dec" size="8" value="0.00" />

Thanks a lot for any help, your time and suggestions.

jsfiddle can facilitate it.

È stato utile?

Soluzione 2

You have a number of problems you need to solve.
Break them down into smaller chunks and tackle it from there.

Only numbers

You could watch the field (check out .on) for a change and then delete any character that's not part of the set [\d] or [0-9], but that could get messy.
A better idea might be to watch for a keydown event and only allow the keys that represent numbers.

The Dot

Trying to dynamically stop the user from deleting the dot is messy, so let's just focus on adding it back in when the field is blurred.
That's pretty easy, right? Just check for a . and if there isn't one, append ".00" to the end of the field.

Decimal Places

This is really the same problem as above. You can use .indexOf('.') to determine if the dot is present, and if it is, see if there are digits after it. If not, append "00" if so, make sure there's 2 digits, and append a "0" if there's only 1.

String Pattern

This could really be solved any number of ways, but you can reuse your search for the decimal place from above to split the string into "Full Dollar" and "Decimal" parts.
Then you can use simple counting on the "Full Dollar" part to add spaces. Check out the Javascript split and splice functions to insert characters at various string indexes.

Good luck!

Altri suggerimenti

Google Translate says he said: "Matus know the těchhle point I stopped, I'm a beginner and do not know what I stand on it all night"

Sounds like you need to read up on some JavaScript and jQuery tutorials. I began with something like this: jQuery for Absolute Beginners: The Complete Series

Really hope this helps.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top