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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    New to the CF scene
    Join Date
    Mar 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question A minor issue with some javascript

    Hi,

    I'm having a small issue. I have an converter that looks like this that I made:

    See this image:



    So, I did that html part within Dreamweaver. The only issue I'm having is getting the Javascript to output the conversions in here.

    Each of the 4 listed outputs I want - metres, feet, inches and millimetres are wrapped with the <p id ="blah> tags.

    I then added the following JavaScript code to the bottom to calculate the conversions:

    Code:
    <script>
    var cm = document.getElementById("cm").value
    
    function convert()
    {
    document.getElementById("metre").innerHTML = "Metres: "+ int(cm)/100
    document.getElementById("metre").innerHTML = "Millimetres: "+ int(cm)/100		
    document.getElementById("metre").innerHTML = "Feet: "+ int(cm)/100	
    document.getElementById("metre").innerHTML = "Inches: "+ int(cm)/100	
    }
    </script>
    So basically I'm trying to get the value that is inputted by the user from the cm field, and then using a function to complete the calculations which will be shown alongside each part.

    What needs to be done to get that javascript working properly, as it never converts the value I place in the form?

    Thanks in advance for your help.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,245
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    Sounds like homework!

    var cm = document.getElementById("cm").value;
    It is unwise to use the same name/id for an HTML element and a Javascript variable.
    This line should be within the function.

    There is no Javascript method "int". You might use parseInt() but there is no point in doing so here. parseInt() is really intended to convert from one number base to another.

    You are using the same id for four different variables!

    Code:
    <script>
    
    function convert() {
    var cms = Number(document.getElementById("cm").value);
    document.getElementById("metre").innerHTML = "Metres: "+ (cms/100).toFixed(2);
    document.getElementById("millimetre").innerHTML = "Millimetres: "+ (cms * 100).toFixed(2); 		
    document.getElementById("feet").innerHTML = "Feet: "+ 	(cms * 0.032808).toFixed(2);
    document.getElementById("inch").innerHTML = "Inches: "+ (cms * 0.39370).toFixed(2);
    }
    </script>
    What if the user enters "XYZ" in the centimetres field? You need to validate that the user entry is actually a number.

    Most people here regard Dreamweaver as rubbish. It produces about the worst and most out of date JavaScript code possible.

    We import more from them than they export to us. - Presenter BBC Radio 1
    Last edited by Philip M; 03-28-2014 at 09:38 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.

  • #3
    New to the CF scene
    Join Date
    Mar 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    Sounds like homework!

    var cm = document.getElementById("cm").value;
    It is unwise to use the same name/id for an HTML element and a Javascript variable.
    This line should be within the function.

    There is no Javascript method "int". You might use parseInt() but there is no point in doing so here. parseInt() is really intended to convert from one number base to another.

    You are using the same id for four different variables!

    Code:
    <script>
    
    function convert() {
    var cms = Number(document.getElementById("cm").value);
    document.getElementById("metre").innerHTML = "Metres: "+ (cms/100).toFixed(2);
    document.getElementById("millimetre").innerHTML = "Millimetres: "+ (cms * 100).toFixed(2); 		
    document.getElementById("feet").innerHTML = "Feet: "+ 	(cms * 0.032808).toFixed(2);
    document.getElementById("inch").innerHTML = "Inches: "+ (cms * 0.39370).toFixed(2);
    }
    </script>
    What if the user enters "XYZ" in the centimetres field? You need to validate that the user entry is actually a number.

    Most people here regard Dreamweaver as rubbish. It produces about the worst and most out of date JavaScript code possible.

    We import more from them than they export to us. - Presenter BBC Radio 1
    Thank you for your assistance to fix the issues in my javascript. I appreciate it.

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Philip M View Post
    var cm = document.getElementById("cm").value;
    It is unwise to use the same name/id for an HTML element and a Javascript variable.
    It is safe enough to do that if you enclose your entire JavaScript inside a function as then the var cm would be a local variable while the id reference is to a global variable. In fact if you do that consistently inside of a function (where all JavaScript belongs) then you will know exactly which variable refers to which id.
    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.

  • #5
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts
    Do you know of any current or recent
    browsers that fail to alert "hello" with
    this code ?

    <div id=div1>hello</div>
    <script>
    alert(div1.innerHTML)
    </script>

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by DaveyErwin View Post
    Do you know of any current or recent
    browsers that fail to alert "hello" with
    this code ?
    It depends on whether you have updated the browser settings to turn off the debugging dialogs. All current browsers can display an alert - some do display additional checkboxes to make debugging easier for those that haven't realised that the browser has built in debugging tools - usually either a checkbox to disable the debugging dialogs for the current page or alternatively to turn off JavaScript completely for the current page.

    I used to just check the disable JavaScript checkbox when people were silly enough to leave those debugging calls in their code. Now I just have the dialogs completely disabled - they are only intended for the site owner's use while testing the page so visitors have no need to see them at all.
    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
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts
    Do you know of any current or recent
    browsers that does not alert true
    with this code ?

    <div id=div1>hello</div>
    <script>
    alert(div1 === document.getElementById("div1"))
    </script>
    It seems document.getElementById
    is not necessary any more.

  • #8
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,075
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Quote Originally Posted by DaveyErwin View Post
    Do you know of any current or recent
    browsers that does not alert true
    with this code ?



    It seems document.getElementById
    is not necessary any more.
    Yeah but it's still good practice to use document.getElementById. I *think* that non-IE browsers just supported the IE way of directly accessing elements by id for backward compatibility.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #9
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,989
    Thanks
    56
    Thanked 557 Times in 554 Posts
    it seems to be in the HTML5 specs...
    5 Loading Web pages — HTML5

  • Users who have thanked xelawho for this post:

    DaveyErwin (03-29-2014)

  • #10
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    That is really antiquated JavaScript code.

    To write it correctly using modern JavaScript you'd have:

    Code:
    <div id=div1>hello</div>
     <script type="application/javascript">
    (function() {
    "use strict";
     alert(div1 === document.getElementById("div1"));
    })();
     </script>
    And then the script would not run at all except in antiquated browsers - where it would return false - because div1 is not defined.

    Of course you ought to be using console.log() instead of alert() for your debugging but that doesn't change the fact that the code will not run at all unless you add var div1; in which case it would run and return false.


    If you want a short way of referencing elements in the page then use:

    Code:
    var $ = function (el,o) {
    "use strict";
    var d = (undefined===o) ? document : o;
    return (/^#\S+$/.test(el)) ? d.querySelector(el) : [].slice.call(d.querySelectorAll(el));
    }
    You can then reference the content using code such as:

    Code:
    var a = $('#div1');
    console.log(a.innerHTML);
    
    var b = $('#div1 .class3');
    b.forEach(function(c) {console.log(c.innerHTML);});
    
    var d = $('.class3', a);
    d.forEach(function(c) {console.log(c.innerHTML);});
    Last edited by felgall; 03-29-2014 at 04:23 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.

  • #11
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,989
    Thanks
    56
    Thanked 557 Times in 554 Posts
    umm... this:
    Code:
    <div id=div1>hello</div>
     <script type="application/javascript">
    (function() {
    "use strict";
     alert(div1 === document.getElementById("div1"));
    })();
     </script>
    alerts true in my versions of Firefox and Chrome, and if you take out the type="application/javascript" it alerts true in IE8 as well...

  • #12
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts
    JavaScript is old news
    better to use ecmascript ...

    <div id=div1>hello</div>
    <script type="application/ecmascript">
    (function() {
    "use strict";
    alert(div1 === document.getElementById("div1"));
    })();
    </script>

  • #13
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by xelawho View Post
    umm... this:
    Code:
    <div id=div1>hello</div>
     <script type="application/javascript">
    (function() {
    "use strict";
     alert(div1 === document.getElementById("div1"));
    })();
     </script>
    alerts true in my versions of Firefox and Chrome, and if you take out the type="application/javascript" it alerts true in IE8 as well...
    Had to think about why it didn't work when I tested it - realised that I was using a browser that properly follows the ECMAScript standards and so doesn't run because div1 is not defined. It is only defined in browsers wanting to emulate the IE4 proprietary call and break your scripts when you try to use those variable names yourself.

    It is a pity that modern JavaScript doesn't disallow global variable references inside of functions as that would fix this bug in Firefox and Chrome. Probably coming in either ES6 or ES7.

    Of course the JavaScript didn't run in IE8 - IE8 only understands jScript and not JavaScript and that's why the long obsolete text/javascript continued to be used that identifies the code as being one of jScript and JavaScript without specifying which. Now that IE8 is almost dead it is possible to consider using the correct application/javascript MIME type - either hard coded in the script tag or defined as the MIME type for all .js files on the server.

    To code that function properly it should have been written as:

    Code:
    <div id=div1>hello</div>
     <script type="application/javascript">
    (function() {
    "use strict";
     var div1; 
     alert(div1 === document.getElementById("div1"));
    })();
     </script>
    Now it will run in all browsers and not just those that pollute the global namespace.
    Always declare all your variables as local to the function or some browsers may break the code by polluting the global namespace with junk.

    I lost count of how many scripts I tested last in IE4,5,6 or 7 where the script worked fine until I tried to run it in a browser that filled the global namespace with excrement.
    Last edited by felgall; 03-29-2014 at 05:01 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.

  • #14
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,989
    Thanks
    56
    Thanked 557 Times in 554 Posts
    Quote Originally Posted by felgall View Post
    ... realised that I was using a browser that properly follows the ECMAScript standards and so doesn't run because div1 is not defined. It is only defined in browsers wanting to emulate the IE4 proprietary call and break your scripts when you try to use those variable names yourself.

    It is a pity that modern JavaScript doesn't disallow global variable references inside of functions as that would fix this bug in Firefox and Chrome. Probably coming in either ES6 or ES7.
    can I ask which browser you test in, because now I tested it in opera and safari and it's still returning true...

  • #15
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,245
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    Quote Originally Posted by felgall View Post
    It is safe enough to do that if you enclose your entire JavaScript inside a function as then the var cm would be a local variable while the id reference is to a global variable. In fact if you do that consistently inside of a function (where all JavaScript belongs) then you will know exactly which variable refers to which id.
    I did say "unwise" That is because there is the possibility of human confusion between the local and global variables with the same name/id. If you are sensible you would not give the same name to two dogs, two children or two anything else. Good practice IMO. By all means make the Javascript id a variant of the HTML - cms and cm, or name and username for example.

    This works, but is bad practice IMO:-

    Code:
    <input id = "text">
    
    <script type = "text/javascript">
    text = "Hello World";  // global variable
    document.getElementById('text').value = text;
    </script>
    Last edited by Philip M; 03-29-2014 at 11:50 AM. Reason: Typo

    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.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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