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 10 of 10

Thread: parseInt method

  1. #1
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    parseInt method

    Im working on learning JavaScript with the help of a text book, below is the current script I am working on regarding handling forms. This script should populate the "Days" field depending on the Month selected. I understand most of it except for the parseInt function. Could anyone help describe it to me? I understand it turns a String into a Value...hmm

    Code:
     
    window.onload = initForm;
    
    function initForm() {
    	document.getElementById("months").selectedIndex = 0;
    	document.getElementById("months").onchange = populateDays;
    }
    
    function populateDays() {
    	var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
    	var monthStr = this.options[this.selectedIndex].value;
    	
    	if (monthStr != "") {
    		var theMonth = parseInt(monthStr);
    					
    		document.getElementById("days").options.length = 0;
    		for(var i=0; i<monthDays[theMonth]; i++) {
    			document.getElementById("days").options[i] = new Option(i+1);
    		}
    	}
    }

    Thank you! I am very interested in learning this and would love any help!
    Last edited by Finch; 12-16-2011 at 07:04 AM. Reason: answered one of my own questions =x

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,151
    Thanks
    203
    Thanked 2,548 Times in 2,526 Posts
    Google is your friend!

    http://www.w3schools.com/jsref/jsref_parseInt.asp


    Quizmaster: In maths, what number is represented by 10 to the power of 3?
    Contestant: Six.

    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.

  • #3
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Yes, Google and I are friends. We get along quite well actually. I suppose I was just looking for a different explanation. But thanks for the comment.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,585
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    I understand it turns a String into a Value...hmm
    Well, yeah. Except a String *is* a Value.

    It turns a string into an INTEGER value, if possible. Integers are whole numbers (-7, 55, 0, -113, 332, etc.). If the function can't convert the string to an integer, then the result is a special value called NaN ("Not a Number").

    Compare parseInt() to parseFloat() andNumber( ).
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    New Coder
    Join Date
    Dec 2011
    Location
    San Francisco, CA
    Posts
    24
    Thanks
    0
    Thanked 5 Times in 5 Posts
    basically, when something returned a number as a string, eg:

    Code:
    function something() { return "100"; }
    var get = something();
    You may not always want to use it as a string, if you need to do math:

    Code:
    var num = get + 1;
    // at this point num wouldn't be 101... because you cant add a string to an integer and expect a mathematically correct result
    However... the following solves the problem:

    Code:
    var num = parseInt(get) + 1;
    Simple.

    This can sometimes be common for parsing out a number out of a number+string combination with pixel values:

    Code:
    var width = "100px";
    var new_width = parseInt(width) + 20;
    var final = new_width + 'px';
    The above will take 100px, remove "px" by parseInt, then add 20 to it, then re-ad "px"

    This way you can do math on some default values stored in elements which do by default contain the dreaded PX.
    Last edited by html-tutorials; 12-17-2011 at 02:08 AM.

  • Users who have thanked html-tutorials for this post:

    Finch (12-17-2011)

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    parseInt is for converting numbers between different bases. The original number can be in anything between base 2 (binary) and base 36. The result will always be base 10 (decimal). You can either specify the base the original number is in as the second parameter you supply to parseInt eg. parseInt('afbc91', 16) or have it assume what base you are translating from by the first character of the string - '0x' means base 16 and '0' means base 8.

    To convert a string to a number use either:

    var num = Number(str);

    or

    var num = +str;
    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
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    In the particular script above (I think this is where I am having trouble understanding the parseInt method), what is the parseint method doing? I will paste the HTML doc that goes along w. this below:

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    	<title>Dynamic Menus</title>
    	<script src="script02.js"></script>	
    </head>
    <body>
    <form action="#">
    	<select id="months">
    		<option value="">Month</option>
    		<option value="0">January</option>
    		<option value="1">February</option>
    		<option value="2">March</option>
    		<option value="3">April</option>
    		<option value="4">May</option>
    		<option value="5">June</option>
    		<option value="6">July</option>
    		<option value="7">August</option>
    		<option value="8">September</option>
    		<option value="9">October</option>
    		<option value="10">November</option>
    		<option value="11">December</option>
    	</select>
    	&nbsp;
    	
    	<select id="days">
    		<option>Day</option>
    	</select>
    </form>
    
    </body>
    </html>
    Thanks for all the help everyone, I am starting to understand it more - In this case, is the parseint is turning the var monthStr into a "number"? What does that actually do?

  • #8
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    Quote Originally Posted by Finch View Post
    Im working on learning JavaScript with the help of a text book
    I'd ditch that text book, if I were you.

    Trying to recreate date logic is pretty much always wrong, and should never be advocated in any learning material. There's already a built-in Date object, and not using it not only makes your code harder to maintain, it will most probably also result in a bunch of generalizations that just don't work in the real world:

    February doesn't always have 28 days. Sometimes it has 29, and if you want to account for that fact in the piece of code you posted, you'll make the problem worse by introducing additional logic that the Date object already provides in the first place.

    Since the Date constructor allows for overflowing values, the logic for determining the number of days in a certain month can be as simple as this:

    PHP Code:
    function monthLength (yearmonth) {
        return new 
    Date(yearmonth 10).getDate();
    }
    alert(monthLength(20111)); // 28
    alert(monthLength(20121)); // 29 
    Code that tries to mimic built-in date logic wastes a ridiculous amount of maintenance cost every year; I'm not nitpicking here — this is a real problem, and any text book that propagates this sort of DIY date logic without any regard to the big picture should be considered harmful.


    And to answer your actual question: parseInt converts its argument to a string, discards everything that doesn't make sense for an integer, and returns a new primitive of type number. See here for how exactly that works: https://developer.mozilla.org/en/Jav...jects/parseInt

    That said, it's pretty much useless in your piece of code, since property names are strings anyway, so you're actually doing a double conversion:

    PHP Code:
    for (var i in [0]) {alert(typeof i);} // string 
    Last edited by venegal; 12-17-2011 at 03:49 PM. Reason: changed monthLength function to an even easier one
    .My new Javascript tutorial site: http://reallifejs.com/
    .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
    .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,151
    Thanks
    203
    Thanked 2,548 Times in 2,526 Posts
    Quote Originally Posted by felgall View Post
    To convert a string to a number use either:

    var num = Number(str);

    or

    var num = +str;
    Or var num = num*1;


    The value returned from a select list value is a string value. But as I see it the values are not used in any case. The code is using selectedIndex which is already a number, so the parseInt() has no purpose in this case. Perhaps that is why you are having trouble understanding it.


    Take a little time to study this code:-

    Code:
    	<select id="months" onchange = "showValue()">
    		<option value="">Month</option>
    		<option value="0">January</option>
    		<option value="1">February</option>
    		<option value="2">March</option>
    		<option value="3">April</option>
    	</select>
    
    
    <script type = "text/javascript">
    
    function showValue() {
    var myArray = ["Jan", "Feb", "Mar", "Apr"];
    var val = document.getElementById("months").value;
    alert (val + "  " + typeof val);
    alert (myArray[val]);  // although val is a string value Javascript will interpret it as a number here
    var si = document.getElementById("months").selectedIndex;
    alert (si + "   " + typeof si);
    alert (myArray[si-1]);
    var txt = document.getElementById("months").options[si].text; 
    alert (txt);  // the text value of the option
    }
    As venegal says, that textbook seems less than instructive.
    Last edited by Philip M; 12-17-2011 at 08:21 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.

  • #10
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    Quote Originally Posted by Philip M View Post
    The value returned from a select list value is a string value. But as I see it the values are not used in any case. The code is using selectedIndex which is already a number, so the parseInt() has no purpose in this case. Perhaps that is why you are having trouble understanding it.
    This doesn't sound right. The value of the selected option is used — namely as an array key — whereas the selectedIndex property is only used to get that value (unnecessarily so, as pointed out in your snippet, since the value of the select itself can be used instead of the value of the selected option).

    Also, this is a bit misleading:

    Quote Originally Posted by Philip M View Post
    Code:
    alert (myArray[val]);  // although val is a string value Javascript will interpret it as a number here
    Internally, all property names (even numerical ones, i.e. array keys) are strings, so there's actually no type coercion going on here.

    So, you're right that parseInt serves no purpose in the OP's code, but for the wrong reason: It's not that the thing is already a number — it's a string, and the reason parseInt is useless here is that a string is perfectly fine for accessing elements of an array.
    Last edited by venegal; 12-17-2011 at 04:18 PM.
    .My new Javascript tutorial site: http://reallifejs.com/
    .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
    .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback


  •  

    Posting Permissions

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