tdced
tdced

Reputation: 19

Inline Javascript works, but doesn't work externally

I am fairly new to JavaScript and I was wondering if anyone can help me with this problem. I have three text boxes, and the first two show first and last name. And I want the last textbox to contain both first and last.

Here's the code:

<!doctype html>
<html>
    <head>
        <title>Javascript Textbox</title>
    </head>
    <body>
        First Name: <input id="fname" type="text" value="John"><br>
        Last Name: <input id="lname" type="text" value="Smith"><br>
        <input id="textbox" readonly>

        <button onclick="textbox.value=fname.value+' '+lname.value">press to see full name</button>

        <script type="text/javascript" src="testing.js"></script>
    </body>

</html>

This works fine, but when I try to use an external file, testing.js and switching onclick="testFunction()", it doesn't work anymore.

testing.js:

function testFunction() {
    var first = document.getElementById("fname").value;
    var last  = document.getElementById("lname").value;
    var textb = document.getElementById("textbox").value;
    textb     = first + " " + last;
}

Upvotes: 0

Views: 171

Answers (3)

Nerdroid
Nerdroid

Reputation: 13966

change your function to

function testFunction() {
    var first = document.getElementById("fname");
    var last = document.getElementById("lname");
    var textb = document.getElementById("textbox");
    textb.value = first.value + " " + last.value;
}

jsfiddle demo

Upvotes: 1

Kai Qing
Kai Qing

Reputation: 18833

http://jsfiddle.net/1vshky4s/

Ultimately your problem is that you are assigning the texb var the value of the text box, then overriding it with a concatenated string, then doing nothing at all with the results.

function testFunction()
{
    var first = document.getElementById("fname").value;
    var last = document.getElementById("lname").value;
    var textb = first + " " + last;

    document.getElementById("textbox").value = textb;
}

actually do something with the textb var and you should be good to go. Check the fiddle.

Upvotes: 1

sergolius
sergolius

Reputation: 438

Move:

<script type="text/javascript" src="testing.js"></script

Into the head of page. You try to bind function, than doesn't exist. script will be loaded after dom.

p.s. Or use 'onload' event if window p.s.s.

Here correct function:

function testFunction()
{
    var first = document.getElementById("fname").value;
    var last = document.getElementById("lname").value;
    var textb = document.getElementById("textbox"); //!

    textb.value = first + " " + last; // here was error

    }

Upvotes: -1

Related Questions