Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  59] [ 4]  / answers: 1 / hits: 24658  / 12 Years ago, sat, december 8, 2012, 12:00:00

I have some inputs on my webapp where we're asking the user to enter percentage values (e.g 10.75%, 23%). Currently, they have to enter these values as decimal (e.g. 0.1075 , 0.23).



This is causing confusion for some users, so I was hoping there was a way I could convert the values to and from these formats (the backend has decimal values, the HTML inputs display the percentage values). Is there a solution to this without having to roll-my-own with javascript or the like?



I didn't see anything in the HTML5 inputs that would do this, and I wasn't able to find a javascript lib that would do it easily.



What way have other people been doing percentage inputs in HTML?






Additional Info



The webapp is using Java/Spring, so the values coming to the HTML page are coming string from the java objects in question, so ideally I'm looking for something that doesn't take any backend coding.






Answer



It turns out that Spring 3.0 will do this automatically. Annotating the fields in question with:



@NumberFormat(style = NumberFormat.Style.PERCENT)
private BigDecimal rate;


Will do all the conversion to and from the input field.


More From » html

 Answers
39

The javascript required is very simple. For example you could store the fraction value of the user's input in a hidden field when the user submits.



​<form id=myForm>
<input type=text id=myPercent name=myPercent />%
<input type=hidden id=myFraction name=myFraction />
<input type=submit />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
<script type=text/javascript>
document.getElementById('myForm').onsubmit = function() {
document.getElementById('myFraction').value =
document.getElementById('myPercent').value / 100;
}
</script>

[#81534] Friday, December 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
richardaydenc

Total Points: 148
Total Questions: 125
Total Answers: 98

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;