Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    New Coder
    Join Date
    Mar 2012
    Posts
    60
    Thanks
    65
    Thanked 0 Times in 0 Posts

    ensure input text block has 6 decimal place

    I want to ensure that my input field on my form always has 6 decimal places even while the user type in numbers.

    Is there an easy way to do this with the key up event?

    What I'm currently doing is - on key up take the value and split it into an array then add on "0" .

    Is there a shorter easier way todo this?

    thanks

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,731
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    I don't see how you can show 6 decimal digits while the user types - onkeyup. It would be best to do this onblur. You need to be aware that a value such as 12.345000 (padded to 6 decimal digits) is a string value and not a number.

    Code:
    <input type = "text" id = "txt1" onblur = "make6()">
    
    <script type = "text/javascript">
    function make6() {
    var val = document.getElementById("txt1").value;
    if (/\./.test(val)) {
    var valsplit = val.split(".");
    var decs = valsplit[1].length;  // number of decimal digits
    
    if (decs >6) {
    valsplit[1] = valsplit[1].substring(0,6);
    decs = 6;
    }
    
    var zeroes = 6-decs;
    for (var i=0; i < zeroes; i++) {
    valsplit[1] += "0";
    }
    
    val = valsplit.join(".")
    alert (val);
    }
    }
    
    </script>
    The earth's Teutonic plates are shifting. - Financial commentator BBC Radio London

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    code-in-time (05-30-2012)

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,465
    Thanks
    0
    Thanked 634 Times in 624 Posts
    or simply use

    <input type="text" id="txt1" onblur ="this.value.toFixed(6)">
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    code-in-time (05-30-2012)

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,731
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Quote Originally Posted by felgall View Post
    or simply use

    <input type="text" id="txt1" onblur ="this.value.toFixed(6)">
    Should be:-

    <input type="text" id="txt1" onblur ="this.value = Number(this.value).toFixed(6)">

    But indeed a much simpler solution!

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    code-in-time (05-30-2012)

  • #5
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,465
    Thanks
    0
    Thanked 634 Times in 624 Posts
    Quote Originally Posted by Philip M View Post
    Should be:-

    <input type="text" id="txt1" onblur ="this.value = Number(this.value).toFixed(6)">

    But indeed a much simpler solution!
    You are right - toFixed is a number method and this.value is a string.

    So the shortest version would be:


    <input type="text" id="txt1" onblur ="this.value = (+this.value).toFixed(6)">
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    code-in-time (05-30-2012)

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,465
    Thanks
    0
    Thanked 634 Times in 624 Posts
    Quote Originally Posted by iBall View Post
    another thing you overlooked is that onblur should be onkeyup according to the op's post 1.
    That will not work though which is why the event used was changed to onblur in all the variants of the answer..

    If you were to attach that to onkeyup and someone was going to enter 315.654321 then they'd get as far as typing the 3 and it would immediately output 3.000000 which isn't at all what they were trying to input. When they press the first backspace to start to go back to fix the number the onkeyup would output 3.000000 and put them at the end of the number again. They'd never be able to enter the second digit of the number.

    The only way to get it to allow anything except single digit numbers followed by .000000 is to attach it to onblur instead of onkeyup.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,465
    Thanks
    0
    Thanked 634 Times in 624 Posts
    Quote Originally Posted by iBall View Post
    Then the op needs to be more specific because he/she is clearly doing it with onkeyup (and you're not) and is just asking if there is an easier/shorter way than the way they are doing it.
    The reason the OP's code doesn't work is because they are using onkeyup when they should be using onblur. Their code would probably work if they made that change but since they didn't actually post their code there's no way to be certain that there are not further problems with their code.

    It is NOT POSSIBLE to do it with onkeyup - for the reason I already gave.
    Last edited by felgall; 05-25-2012 at 08:17 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,731
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Quote Originally Posted by iBall View Post
    the op says he/she is using onkeyup.

    Like I said, they need to be more specific in what they want which should include posting the code they have so far.
    In the past iBall has often said that he does not believe what people say in these posts! But he does claim to believe any rubbish if it pleases him to do so. Anyone claiming any understanding of coding would appreciate that onkeyup cannot possibly work in this context. If anyone else made such a silly error iBall would vomit his bile in delight all over the forum.

    The great advantage of being on iBall's ignore list is that he cannot seize on something in one of my posts to start a pointless and belligerent argument. And I can repeatedly remind everyone of the fact that he has previously been banned from this forum on several occasions for flaming and threatening people with litigation.
    Last edited by Philip M; 05-25-2012 at 08:28 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #9
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    OK, I am not a javascript expert by any means at all. I know I've learned loads of the bad habits and I know I will probably take a lot of heat from a few people in this thread about my code... but someone said it couldn't be done (which seemed wrong to me) so I spent a little while trying to make something work with the onkeyup event.

    So before anyone starts in on me, I KNOW that I have used global variables. I KNOW that the script is not unobtrusive (I have inline script and I didn't use a listener...heck, I even used an onload attribute on the body tag which I NEVER do in real practice). I KNOW that there is a lot of room for optimization. I KNOW that many parts of the script are redundant because I built it in a mess. I KNOW that there are vestiges of features I haven't implemented but was planning to at the outset. I know...but I was focused more on the process than the polish. This is a garbage script, yes. But the basic functionality works, and it uses the onkeyup event as the OP was requesting.

    So, without further warning, I offer a half-baked solution using the "onkeyup" approach for this request (works in IE9 and FF7.0 - I haven't tested it in other browsers):

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>6 Decimal Notation on Keyup</title>
    <script type="text/javascript">
    function in_array(needle,haystack){
    	var length=haystack.length;
    	for(var i=0;i<length;i++){
    		if(haystack[i]==needle) return true;
    	}
    	return false;
    }
    function getCaretPosition(elm){
    	if(elm.selectionStart){
    		return elm.selectionStart;
    	}
    	else if(!document.selection){
    		return 0;
    	}
    	var c = "\001",
    	sel = document.selection.createRange(),
    	dul = sel.duplicate(),
    	len = 0;
    	dul.moveToElementText(elm);
    	sel.text = c;
    	len = dul.text.indexOf(c);
    	sel.moveStart('character',-1);
    	sel.text = "";
    	return len;
    }
    function setCaretPosition(elem,caretPos){
    	if(elem != null){
    		if(elem.createTextRange){
    			var range = elem.createTextRange();
    			range.move('character', caretPos);
    			range.select();
    		}
    		else{
    			if(elem.selectionStart){
    				elem.focus();
    				elem.setSelectionRange(caretPos, caretPos);
    			}
    			else{
    				elem.focus();
    			}
    		}
    	}
    }
    //the initial cursor position is set to "0" (start of the field)
    var cursor_position=0;
    //your "safe value" is set to the least case option (or your starting field value if you want to have another number as the base case
    var safe_value="0.000000";
    //the field will accept keycodes for end, home, arrow keys, backspace, delete, 0-9 and "." on main keyboard, and 0-9 and "." on numpad (note the keycodes used are for US keyboards - you may need to switch values OR, better still, change the approach so that you test for actual values entered rather than keystrokes)
    var keycodes=new Array(35,36,37,38,39,40,8,46,48,49,50,51,52,53,54,55,57,190,96,97,98,99,100,101,102,103,104,105,110);
    function set_decimals(e,elm,decimals){
    	var unicode=e.keyCode? e.keyCode : e.charCode;
    	var raw_contents=elm.value;
    	var contents=(+raw_contents);
    	if(in_array(unicode,keycodes)){
    		//if the key pressed is in our list of keys to allow, we process it accordingly
    		if(unicode!=35 && unicode!=36 && unicode!=37 && unicode!=38 && unicode!=39 && unicode!=40){
    			//if we are doing something OTHER THAN navigating with home/end or the arrow keys
    			if(unicode==110 || unicode==190){
    				//if a decimal key has just been pressed...
    				if(raw_contents.substr((cursor_position+1),1)=="."){
    					//if our cursor is to the IMMEDIATE LEFT of the decimal point when we type the character, we have a valid press of the key and we need to jump to the other side of the decimal point
    					raw_contents=raw_contents.substr(0,cursor_position)+raw_contents.substr(cursor_position+1);
    					contents=(+raw_contents);
    					cursor_position++;
    					setCaretPosition(elm,cursor_position);
    				}
    				else{
    					//otherwise, we have added a second (and inappropriate) decimal point which must be removed...
    					raw_contents=raw_contents.substr(0,cursor_position)+raw_contents.substr(cursor_position+1);
    					contents=(+raw_contents);
    					elm.value=contents;
    					setCaretPosition(elm,cursor_position);
    				}
    			}
    			else if((unicode==8 || unicode==46) && raw_contents.indexOf(".")==-1){
    				//if backspace or delete has been pressed AND there is suddenly no decimal point (or in othe words, we are intending to move our curosr from one side of the decimal point to the other) we replace the deleted decimal point and move the cursor around by one character position...
    				if(unicode==8){
    					//if it was a backspace keystroke
    					cursor_position--;
    				}
    				//replace the decimal point
    				raw_contents=raw_contents.substr(0,cursor_position) + "." + raw_contents.substr(cursor_position,raw_contents.length);
    				contents=(+raw_contents);
    				if(raw_contents.substr(raw_contents.indexOf(".")+1,raw_contents.length)=="000000"){
    					//if the result is an integer, we need to turn it into a string in order to avoid being "locked" into a position in front of the decimal point
    					contents=contents+".0";
    				}
    				//set the input field's value
    				elm.value=contents;
    				if(unicode==46){
    					//if it was a delete keystroke
    					cursor_position++;
    				}
    				//set our current cursor position
    				setCaretPosition(elm,cursor_position);
    			}
    			else if((unicode!=8 && unicode!=46) && cursor_position==0 && raw_contents.substr(1,raw_contents.indexOf(".")-1)=="0"){
    				//if we have NOT just used backspace or delete and if we are at the start of the string and the only other integer before the decimal is "0" then we overwrite the "0" character
    				raw_contents=raw_contents.substr(0,1)+raw_contents.substr(2,raw_contents.length);
    				contents=(+raw_contents);
    				elm.value=contents;
    				cursor_position=1;
    				setCaretPosition(elm,cursor_position);
    			}
    			//update the cursor position
    			cursor_position=getCaretPosition(elm);
    			//treat the data - if it's a number we use toFixed and if it is a string we back-fill the string with zeros to the desired result
    			try{
    				//for numeric results
    				elm.value=contents.toFixed(6);
    				if(elm.value=="NaN"){
    					elm.value="0.000000";
    					cursor_position=0;
    					setCaretPosition(elm,cursor_position);
    				}
    			}
    			catch(err){
    				//for string results...
    				var filler="";
    				for(i=0;i<5-contents.substr(contents.indexOf('.')+1,contents.length);i++){
    					filler+="0";
    				}
    				elm.value=contents+filler;
    			}
    			//update our last known "safe" value...
    			safe_value=elm.value;
    			//reset our cursor position now that the text field's value has been overwritten (or else we will end up with our cursor being dropped at the end of the content)
    			setCaretPosition(elm,cursor_position);
    		}
    		else{
    			//otherwise, if we are navigating we update our cursor_position and do nothing else
    			cursor_position=getCaretPosition(elm);
    		}
    	}
    	else{
    		//if key pressed is not in our list of approved keys, we restore the value to the previous "safe" version of the data and drop the cursor right back where it was and let the user try again...
    		elm.value=safe_value;
    		setCaretPosition(elm,cursor_position);
    	}
    }
    </script>
    <style type="text/css">
    *{margin:0;padding:0;}
    body{padding:10px;font-family:verdana;font-size:12px;}
    h1{font-size:20px;fonot-weight:bold;margin-bottom:10px;}
    p{width:500px;margin-bottom:10px;}
    input,select,textarea{display:block;margin-bottom:10px;font-family:'times new roman';font-size:14px;}
    </style>
    </head>
    <body onload="document.getElementsByTagName('input')[0].focus();">
    <h1>Try this:</h1>
    <form action="" method="post" onsubmit="return false;">
      <div>
        <input type="text" name="decimal" onkeyup="set_decimals(event,this,6);" onclick="cursor_position=getCaretPosition(this);" value="0.000000" />
      </div>
    </form>
    <p>There are certainly some bugs to work out with this (for instance, pasting does not work correctly...and try typing so quickly that your first number is not keyed up before the second number has been pressed and see what happens) but this is a working start...</p>
    <p>You can add code to clean up those irregularities as well as to modernize the approach (get rid of globals and "package" the script as well as make it unobtrusive). But this is my layman's attempt at the solution so I haven't bothered to spend a lot of time on cleanup.</p>
    </body>
    </html>
    Note that the "finer points" of this have not been added...at all. This is absolutely not an example of my best work. Note also that I got half way through this script relying on keycodes before it struck me that this is dependent on the user's region for their keyboard. The more sound approach would be to compare the field values before and after keyup events are fired to see what has been entered and work with that. But I didn't feel like going back once I started so this is really more "proof of concept" than "recommended practice."

    The only real hitch was tracking the cursor/caret position and acting accordingly but I found a helper script or two through google to tackle that issue.

    And yes, I know, I know, I know...bad javascript! Feel free to clean it up and flesh it out to make it something that will pass muster. Personally, I'm sick of looking at it for today!
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • #10
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,465
    Thanks
    0
    Thanked 634 Times in 624 Posts
    Quote Originally Posted by Rowsdower! View Post
    but someone said it couldn't be done (which seemed wrong to me) so I spent a little while trying to make something work with the onkeyup event.
    How many cars have you driven off a cliff with miles of curtain material attached in order to find out which ones can fly? (A reasonable analogy to what you are doing with that code).

    Some browsers that you haven't tested with don't allow you to reposition the cursor within the field and so even with 10000 times the amount of code you have there the onkeyup still wouldn't work.

    Anyway, fixing the value at six decimal places is formatting and formatting shouldn't be applied until AFTER the field has been input. You should only be using onkeyup for filtering functions such as discarding everything except numbers and .

    The shortest version that actually works properly in all browsers that support JavaScript is:

    Code:
    <input type="text" id="txt1" onblur ="this.value = (+this.value).toFixed(6)">
    Someone trying to enter 315.654321 into the field who types the 3 and sees 3.000000 displayed might try backspacing to fix the error in their input that the onkeyup has created but is just as likely to decide that the page is stuffed and go elsewhere.
    Last edited by felgall; 05-25-2012 at 09:53 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    Philip M (05-26-2012)

  • #11
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    Quote Originally Posted by felgall View Post
    How many cars have you driven off a cliff with miles of curtain material attached in order to find out which ones can fly? (A reasonable analogy to what you are doing with that code).
    It may help to read up re: "reasonable" and consider editing your post. Do you even honestly believe your analogy is reasonable?

    Anyway, I wrote a half page of caveats and "this is not fit for mass consumption" warnings about that sample script just to try to keep the curmudgeons off of my back. Apparently, this didn't work for you?

    It's advertised as a garbage script, but one that is working on a rudimentary level in IE9 and FF7. If you can fault me for something that I claimed the script would do in those browsers (which is an extremely short list), but which it in fact does not do in those browsers, then go ahead and point out the faults. I wouldn't be surprised to hear of them.

    Quote Originally Posted by felgall View Post
    Some browsers that you haven't tested with don't allow you to reposition the cursor within the field...
    Fair enough. See? I'm not even surprised to hear this, which is why I listed the two browsers I actually had it tested and working in. It was never advertised as cross-browser compatible. But this is still a constructive thing to point out for the OP, so kudos. In fact, had your reply consisted of nothing other than this part of this one sentence I wouldn't have needed to write this lengthy response at all.

    Quote Originally Posted by felgall View Post
    ...and so even with 10000 times the amount of code you have there the onkeyup still wouldn't work.
    But now I have to say again that if someone really cared to work on it then switching to a 2-input system would fill the bill and allow an "as you type" formatting even in browsers that do not support repositioning the cursor. The script would need a significant rewrite in order to accommodate, but the larger point is (again) that the effect can still be achieved. And after all, it looks as though it is the effect itself that the OP is after:

    I want to ensure that my input field on my form always has 6 decimal places even while the user type in numbers.
    If the OP returns and says otherwise then fine. But for now this is specifically what was requested and it is what we should strive to provide to the OP until the request changes.

    [Besides which, if you had a problem with the practice of formatting the number while the user typed, why not bring that opinion to the OP to start with in your initial reply? Is this a recent invention of yours or were you withholding a solution because you don't like the feature being requested?]


    Quote Originally Posted by felgall View Post
    Anyway, fixing the value at six decimal places is formatting and formatting shouldn't be applied until AFTER the field has been input. You should only be using onkeyup for filtering functions such as discarding everything except numbers and .
    You are attempting to impose your extremely narrow opinion of this on the OP. The OP specifically requested that functionality and for heaven's sake it's his call to make. Do you similarly begrudge people the right to add commas to their users' numbers as they are typed? What about formatting phone numbers as they are typed? Do you forbid all of these practices or is this grudge of yours only reserved only for decimal notation (significant figures)? Any one of these practices is no less valid than any of the others.

    Quote Originally Posted by felgall View Post
    Someone trying to enter 315.654321 into the field who types the 3 and sees 3.000000 displayed might try backspacing to fix the error in their input that the onkeyup has created but is just as likely to decide that the page is stuffed and go elsewhere.
    Now in principle you are arguing that the user comes into the page seeing an input field that already reads "0.000000" and has a blinking cursor in front of the leading zero. They press the "3" key and immediately give up because the leading zero has been replaced with the "3" they typed and the cursor is now located behind the "3" character and in front of the decimal point? Personally, I would doubt it. I think they juuust might try hitting the next digit to see what happens, if they even stopped to look at all.

    First of all, if that actually did become a problem then you could simply not show the decimal notation until after a "." key had been struck. Problem solved. Simple. But this is (again) not what the OP asked for. He said 6 decimal placed were "always" to be shown.

    But even if you are 100% correct about this and even if there wasn't an easy way to combat the "problem," and even if the word "always" hadn't appeared in the OP's request...the plain fact is that this is not even remotely important to us as people answering a forum question. It's not our call to make.

    A developer can choose to implement whatever features they want to implement in their own website. This includes setting table column widths manually (remember?) and even formatting numbers for a user while they are still typing. None of this is in the domain of things that you can attempt to forbid a developer to do while maintaining any guise of "moral" authority.

    If my solution is not cross-browser friendly (and you say it isn't which I will have no trouble in believing) then your next move should have been to note that problem (which you did) and - if you care to be productive - offer a solution that IS cross-browser friendly and still does what the OP requested. Otherwise you're just blowing the same stale air around this room again and again and nothing valuable is being added to the discourse.

    You stated to iBall (twice) that no onkeyup soultion was possible:

    That will not work though which is why the event used was changed to onblur in all the variants of the answer...The only way to get it to allow anything except single digit numbers followed by .000000 is to attach it to onblur instead of onkeyup.
    It is NOT POSSIBLE to do it with onkeyup
    You're still wrong. You are forcing me to keep telling you that you're wrong, too. That's just silly. It would be simpler if you would just quietly concede the fact that an onkeyup solution is workable (even if inconvenient) and then get into the game and actually help the OP to create one.

    There is a saying: It's easier to eat crow while it's still warm.
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • Users who have thanked Rowsdower! for this post:

    iBall (05-26-2012)

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,731
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Quote Originally Posted by code-in-time View Post
    Is there an easy way to do this with the key up event?
    Is there a shorter/easier way to do this?
    The correct answer is no - there is no shorter/easier way to do this using the keyup event. There is (or may be) a long-winded, complicated, inconvenient and buggy way to do it using onkeyup. The easy solution using onblur has been indicated. The OP may choose between them.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    code-in-time (05-30-2012)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •