html5 입력 유형 번호로 부동 소수점 및 소수 구분 기호를 처리하는 방법
주로 모바일 브라우저 용 웹 앱을 구축하고 있습니다. 숫자 유형의 입력 필드를 사용하므로 대부분의 모바일 브라우저는 더 나은 사용자 경험을 위해 숫자 키보드 만 호출합니다. 이 웹 응용 프로그램은 주로 소수점이 아닌 쉼표가있는 영역에서 사용되므로 소수점 구분 기호를 모두 처리해야합니다.
이 모든 혼란을 점과 쉼표로 덮는 방법은 무엇입니까?
내 발견 :
데스크톱 크롬
- 입력 유형 = 숫자
- 사용자는 "4,55"를 입력 필드에 입력
$("#my_input").val();
"455"를 반환- 입력에서 올바른 값을 얻을 수 없습니다
데스크탑 파이어 폭스
- 입력 유형 = 숫자
- 사용자는 "4,55"를 입력 필드에 입력
$("#my_input").val();
"4,55"를 반환- 괜찮습니다, 쉼표를 점으로 바꾸고 올바른 부동 소수점을 얻을 수 있습니다
안드로이드 브라우저
- 입력 유형 = 숫자
- 사용자는 "4,55"를 입력 필드에 입력
- 입력에 포커스가 없으면 값이 "4"로 잘립니다.
- 사용자에게 혼란
윈도우 폰 8
- 입력 유형 = 숫자
- 사용자는 "4,55"를 입력 필드에 입력
$("#my_input").val();
"4,55"를 반환- 괜찮습니다, 쉼표를 점으로 바꾸고 올바른 부동 소수점을 얻을 수 있습니다
사용자가 쉼표 또는 점을 소수점 구분 기호로 사용할 수 있고 더 나은 사용자 경험을 제공하기 위해 html 입력 유형을 숫자로 유지하려는 경우 이런 종류의 상황에서 "모범 사례"는 무엇입니까?
주요 이벤트를 바인딩하면서 쉼표를 "즉석에서"점으로 변환 할 수 있습니까? 숫자 입력과 함께 작동합니까?
편집하다
Currenlty 나는 해결책이 없습니다. 유형이 숫자로 설정된 입력에서 부동 소수점 값 (문자열 또는 숫자)을 얻는 방법. 최종 사용자가 "4,55"를 입력하면 Chrome은 항상 "455"를 반환하고 Firefox는 "4,55"를 반환합니다.
또한 Android (테스트 4.2 에뮬레이터)에서 "4,55"를 입력하여 필드를 입력하고 다른 곳으로 포커스를 변경하면 입력 한 숫자가 "4"로 잘립니다.
위의 답변에서 누락 된 것은 step
속성에 다른 값을 지정해야한다는 것 입니다 1
. 기본값은 입니다. 입력의 유효성 검증 알고리즘이 부동 소수점 값을 허용하도록하려면 단계를 적절하게 지정하십시오.
예를 들어, 달러 금액을 원했기 때문에 다음과 같은 단계를 지정했습니다.
<input type="number" name="price"
pattern="[0-9]+([\.,][0-9]+)?" step="0.01"
title="This should be a number with up to 2 decimal places.">
jQuery를 사용하여 값을 검색하는 데 아무런 문제가 없지만 DOM API를 사용하여 요소의 validity.valid
속성 을 얻는 것이 유용하다는 것을 알 수 있습니다.
소수점과 비슷한 문제가 있었지만 문제가 있음을 깨달은 이유는 Twitter Bootstrap이 잘못된 값으로 숫자 입력에 추가하는 스타일 때문이었습니다.
다음은 step
속성을 추가 하면 작동 한다는 것을 보여주는 바이올린 이며 현재 값이 유효한지 테스트합니다.
TL; DR : 속성의 기본값은이므로 부동 소수점 값으로 설정하십시오 .step
1
참고 : 쉼표는 나를 검증하지 않지만 OS 언어 / 지역 설정을 쉼표를 소수점 구분 기호로 사용하는 곳으로 설정하면 작동합니다. *주의 사항 * : Ubuntu / Gnome 14.04의 OS 언어 / 키보드 설정 * 독일어 *의 경우에는 해당되지 않았습니다.
w3.org에 따르면 숫자 입력 의 value 속성은 부동 소수점 숫자 로 정의됩니다 . 부동 소수점 숫자의 구문은 점을 소수 구분 기호로만 허용하는 것으로 보입니다.
도움이 될만한 몇 가지 옵션을 아래에 나열했습니다.
1. 패턴 속성 사용
으로 패턴 속성 당신은 HTML5 호환 방법으로 정규 표현식에 허용되는 형식을 지정할 수 있습니다. 여기서 패턴이 실패 할 경우 쉼표 문자가 허용되고 유용한 피드백 메시지를 지정할 수 있습니다.
<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
참고 : 브라우저 간 지원은 많이 다릅니다. 완전하거나 부분적이거나 존재하지 않을 수 있습니다.
2. JavaScript 검증
예를 들어 쉼표를 바꾸거나 모두 함께 확인 하는 onchange (및 / 또는 blur ) 이벤트에 간단한 콜백을 바인딩하려고 할 수 있습니다.
3. 브라우저 유효성 검사 비활성화 ##
Thirdly you could try to use the formnovalidate attribute on the number inputs with the intention of disabling browser validation for that field all together.
<input type="number" formnovalidate />
4. Combination..?
<input type="number" pattern="[0-9]+([,\.][0-9]+)?"
name="my-num" formnovalidate
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
Whether to use comma or period for the decimal separator is entirely up to the browser. The browser makes it decision based on the locale of the operating system or browser, or some browsers take hints from the website. I made a browser comparison chart showing how different browsers support handle different localization methods. Safari being the only browser that handle commas and periods interchangeably.
Basically, you as a web author cannot really control this. Some work-arounds involves using two input fields with integers. This allows every user to input the data as yo expect. Its not particular sexy, but it will work in every case for all users.
Use valueAsNumber
instead of .val()
.
input . valueAsNumber [ = value ]
Returns a number representing the form control's value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an INVALID_STATE_ERR exception if the control is neither date- or time-based nor numeric.
I have not found a perfect solution but the best I could do was to use type="tel" and disable html5 validation (formnovalidate):
<input name="txtTest" type="tel" value="1,200.00" formnovalidate="formnovalidate" />
If the user puts in a comma it will output with the comma in every modern browser i tried (latest FF, IE, edge, opera, chrome, safari desktop, android chrome).
The main problem is:
- Mobile users will see their phone keyboard which may be different than the number keyboard.
- Even worse the phone keyboard may not even have a key for a comma.
For my use case I only had to:
- Display the initial value with a comma (firefox strips it out for type=number)
- Not fail html5 validation (if there is a comma)
- Have the field read exactly as input (with a possible comma)
If you have a similar requirement this should work for you.
Note: I did not like the support of the pattern attribute. The formnovalidate seems to work much better.
uses a text type but forces the appearance of the numeric keyboard
<input value="12,4" type="text" inputmode="numeric" pattern="[-+]?[0-9]*[.,]?[0-9]+">
the inputmode tag is the solution
When you call $("#my_input").val();
it returns as string variable. So use parseFloat
and parseInt
for converting. When you use parseFloat
your desktop or phone ITSELF understands the meaning of variable.
And plus you can convert a float to string by using toFixed
which has an argument the count of digits as below:
var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01
My recommendation? Don't use jQuery at all. I had the same problem as you. I found that $('#my_input').val()
always return some weird result.
Try to use document.getElementById('my_input').valueAsNumber
instead of $("#my_input").val();
and then, use Number(your_value_retrieved)
to try to create a Number. If the value is NaN, you know certainly that that's not a number.
One thing to add is when you write a number on the input, the input will actually accept almost any character (I can write the euro sign, a dollar, and all of other special characters), so it is best to retrieve the value using .valueAsNumber
instead of using jQuery.
Oh, and BTW, that allows your users to add internationalization (i.e.: support commas instead of dots to create decimal numbers). Just let the Number()
object to create something for you and it will be decimal-safe, so to speak.
Sounds like you'd like to use toLocaleString() on your numeric inputs.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString for its usage.
Localization of numbers in JS is also covered in Internationalization(Number formatting "num.toLocaleString()") not working for chrome
'Programming' 카테고리의 다른 글
핑 응답 "요청 시간이 초과되었습니다." (0) | 2020.07.14 |
---|---|
JNI에서 Java로 배열을 반환하는 방법은 무엇입니까? (0) | 2020.07.14 |
Maven에서 외부 속성 파일을 읽는 방법 (0) | 2020.07.14 |
스칼라 열거 이해 (0) | 2020.07.14 |
Firebase에서 모든 노드 데이터를로드하지 않고 노드의 자식 수를 얻는 방법이 있습니까? (0) | 2020.07.14 |