user1142285
user1142285

Reputation: 119

Checking the text input before triggering event in JavaScript

I am trying to create a text-based adventure game. I managed to figure out how to make text output in html's textarea through simple onclick button, but now I am trying to do something new. I am having trouble with doing same thing but with input text where users can write anything in the box and then click on the button. Right now, I am trying to make this program to check the user input against some flag (in this case, I set my flag equal to 'pizza') before it does something. Unfortunately, my code doesn't work at all. I think I don't completely understand how the input is being passed around in JavaScript's functions.

The JavaScript part:

function record(test) {
            var input = document.getElementById('filename');
            fileName = input.value;
            if (fileName == "pizza") {
            var obj=document.getElementById(test);
            obj.value="is this showing up in the textarea???"; 
            }
                        else {obj.value="wrong password!"; }
 
        }

The html part:

<input name="filename" id="filename" type="text">

<a id="record_button" onclick="record('textarea1');" href="javascript:void(0);" title="Record">Perform Action</a>

<textarea wrap="virtual" cols="73" rows="10" id="textarea1"></textarea>

Upvotes: 0

Views: 122

Answers (2)

Snuffleupagus
Snuffleupagus

Reputation: 6715

The problem is this block with your else statement, obj isn't declared. Because you have obj defined in the if statement above it is exclusive to that scope. Just define obj right above the if block.

--

function record(test) {
    var input = document.getElementById('filename');
    fileName = input.value;
    var obj=document.getElementById(test);
    if (fileName == "pizza") { 
        obj.value="is this showing up in the textarea???"; 
    }
    else {
        obj.value="wrong password!";
    }
}

Upvotes: 2

user1726343
user1726343

Reputation:

Add an event listener using JS:

document.getElementById('record_button').onclick=function(){
    record('textarea1');
}

Also, there were a couple things wrong with your function. Here it is with corrections:

function record(test) {
    var input = document.getElementById('filename');
    fileName = input.value;
    var obj = document.getElementById(test);
    if (fileName == "pizza") {
        obj.value = "is this showing up in the textarea???";
    }
    else {
        obj.value = "wrong password!";
    }

}
  1. You were using document.getElementByID on the second line, which is incorrect capitalisation
  2. You were only defining obj conditionally, so the else clause always threw an exception.

Here is a demonstration: http://jsfiddle.net/uQpp7/1/

Upvotes: 1

Related Questions