2

I'm having a strange behavior in jquery.

I'd like to get the value of a input field (type number). It's easier to show it with an example.

The function throws back an empty string when the value contains a comma.

$("#input[type='number']").on('change',function() {
            alert($(this).val());
        });

Why?

Thanks in advance

7
  • 3
    Because for example, 1,2, is not a number. Commented Sep 30, 2014 at 14:53
  • I've tried your code and it works, I've only removed the #. Could you share your html? Commented Sep 30, 2014 at 14:55
  • @Ben I know number 1,2 isn't a number but I need to treat this to replace comma with point. Or do you know any other method to do that? Commented Sep 30, 2014 at 15:01
  • 1
    @Manuel Then maybe using type="number" isn't the solution. Try using a normal textbox, and formatting/rejecting as they type (or on the change event) Commented Sep 30, 2014 at 15:07
  • 2
    1,2 would be considered a number in locales where the comma represents a decimal "point" Commented Sep 30, 2014 at 15:32

2 Answers 2

4

HTML5's spec doesn't allow commas:

value = floating-point number
   A string representing a number

floating-point number:

A floating-point number consists of the following parts, in exactly the following order:

    1. Optionally, the first character may be a "-" character.
    2. One or more characters in the range "0—9".
    3. Optionally, the following parts, in exactly the following order:
        1. a "." character
        2. one or more characters in the range "0—9"
    Optionally, the following parts, in exactly the following order:
        1. a "e" character or "E" character
        2. optionally, a "-" character or "+" character
        3. One or more characters in the range "0—9".
Sign up to request clarification or add additional context in comments.

7 Comments

Does this take into account localisation? Some countries use a comma as the decimal separator.
As written, there's nothing in the spec to allow for it. A browser MIGHT choose to translate a local format into HTML5-allowable format, but that's undefined behavior.
Well, my problem is to replace comma with point because I need to add my data into an sql database, is there any way?
prompt for type=text instead and validate the number separately.
exactly what ian said. "I have a banana, but need to use a hammer. how can I turn the banana into a hammer? I don't want to change the banana"
|
-1

Add this to the input: step="0.01"

so something like:

<input type="number"  step="0.01" />

Then 0.10 will be valid, I am not sure if comma will be treated as valid if your operating system use decimals as comma separated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.