Shilpa Gurnani
Shilpa Gurnani

Reputation: 61

Not Getting HTML TextBox Value in Javascript function? Have searched, but didn't find convincing answer

I'm a beginner trying to get the HTML from a textbox to be used in an if/else statement. This is my HTML code:

    <label id="label1">
    Enter any Number:
</label>
<input type="button" id="Button1"  value="button" />
    <input type="text" id="TextBox1" name="myname" />

And my JavaScript code is:

    <script type="text/javascript">
//<![CDATA[
var buttonElement = document.getElementById("Button1");
var txt_value =document.getElementById("TextBox1").value;
buttonElement.addEventListener('click', function() { Clicked(txt_value) }, false);

function Clicked(txt_value) {

    if (txt_value == 7) {
        alert("You are 7");
    }
    else { alert("You are not 7"); }
}
//]]>
    </script>

I observed that

    var txt_value =document.getElementById("TextBox1");

and then

      buttonElement.addEventListener('click', function() { Clicked(txt_value.value) }, false);

The above example works absolutely fine.

Can someone please tell me what is wrong with:

    var txt_value =document.getElementById("TextBox1").value;

I don't know why I'm getting an empty txt_value

Upvotes: 0

Views: 579

Answers (2)

Split Your Infinity
Split Your Infinity

Reputation: 4229

Move the getting of the value into the click handler...

var textbox1 = document.getElementById("TextBox1");

document.getElementById("Button1").onclick = function () {
    var txt_value = textbox1.value;

    if (parseInt(txt_value, 10) === 7) {
        alert("You are 7");
    } else { 
        alert("You are not 7"); 
    }
};

Now you get the value that is in the textbox when the page loads.

Here is a JSFiddle to test this.

Update Improved the efficiency by caching the textbox. Removed the addEventListener to an onclick (more browser support)

Upvotes: 1

Icarus
Icarus

Reputation: 63956

The reason is that you are getting the value in txt_value before the user enters anything; hence the value is always empty.

IF you change your code to this:

var txt_value =document.getElementById("TextBox1");//removed .value

And the function Clicked to:

function Clicked(txt_value) {

    if (txt_value.value == 7) { //added .value
        alert("You are 7");
    }
    else { alert("You are not 7"); }
}

Should work.

Here's a jsfiddle

Upvotes: 1

Related Questions