Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript alert statement with string & int

Tags:

javascript

Im a newbie to Javascript and trying to debug a simple js function..I need to get the value of x through the alert statement but it doesn't display correctly..How to concatenate a string and int as in this case..

<html>
    <head>
    </head>
    <body>
        <script>
            function displaydate()  
            {
                document.getElementById("test").innerHTML='first line changed';
                document.getElementById("test1").innerHTML='second line changed';
                var x = 5;
                alert("Value of x" + String.valueOf(x));
            }
        </script>
        <p id="test">this is the 1st line</p>
        <p id="test1">this is the 2nd line</p>
        <button type="button" onclick="displaydate()">clickme!</button>

    <body>
</html>

New code:

<html>
    <head>
    </head>
    <body>
        <script>
            function displaydate()  
            {
                document.getElementById("test").innerHTML='first line changed';
                document.getElementById("test1").innerHTML='second line changed';
                var x = 5;
                alert("Value of x=" + x);
                var cars=new Array();
                cars[0]='car';
                cars[1]='Volvo';
                alert("Value of arrary 1 var=' + cars[0]);
                //alert("Value of arrary 2 var='+cars[1]);
            }
        </script>
        <p id="test">this is the 1st line</p>
        <p id="test1">this is the 2nd line</p>
        <button type="button" onclick="displaydate()">clickme!</button>

    <body>
</html>
like image 329
user1050619 Avatar asked Feb 25 '13 17:02

user1050619


1 Answers

alert("Value of x" + x);

JavaScript is a dynamic language. The conversion is done automatically for you. When you do something like "var x = string + int"

Update

The reason your alert is failing now is because you start the alert with a double quotation mark and end the string piece of the alert with a single quote.

like image 133
Mike Thomsen Avatar answered Sep 27 '22 21:09

Mike Thomsen