0

I am beginning to experience the fabulous world of Javascript, I am making a html file with a javascript function with a box, the fact is that the alert does not show what goes into the text field, what am I doing wrong ?, this is my code.

<html>
    <head>
        <script>
        function showMe()
        {
            var nombre= cnombre.value;
            alert("You are "+ nombre);
            cnombre.value="";
            cnombre.focus();
        }
        </script>
    </head> 

    <body>  
            Name:<input type ="text" name="cnombre" 
    size="30">
            <input type="button" value="Go"
    onClick=showMe();>

    </body>
</html>

2 Answers 2

1

Changed your code to give the textbox an id and then retrieve the textbox from the DOM by that id. This should work for you:

<html>
<head>
    <script>
    function showMe() {
    var nombre = document.getElementById('cnombre');
    alert("You are " + nombre.value);
    nombre.value = "";
    nombre.focus();
}
    </script>
</head> 

<body>  
        Name:<input type ="text" id="cnombre" name="cnombre" 
size="30">
        <input type="button" value="Go"
onClick=showMe();>

</body>

Sign up to request clarification or add additional context in comments.

Comments

0

You can't access the textbox like that. See http://jsfiddle.net/GUB3E/ for a working sample based on your code.

Note the id="cnombre" added to the textbox and the use of document.getElementById().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.