stored context in a JQuery variable does not work
The following works fine:
$(function() {
EnableDisableButtons();
$('#TextBox1').keyup(function() {
EnableDisableButtons();
});
});
function EnableDisableButtons() {
var len = $('#TextBox1').val().length;
if (len == 0) {
$("#Button1").attr("disabled", "disabled");
}
else {
$("#Button1").attr("disabled", "");
}
}
But the following does not work at all:
var txt = $('#TextBox1');
$(function() {
EnableDisableButtons();
txt.keyup(function() {
EnableDisableButtons();
});
});
function EnableDisableButtons() {
var len = txt.val().length;
if (len == 0) {
$("#Button1").attr("disabled", 开发者_开发百科"disabled");
}
else {
$("#Button1").attr("disabled", "");
}
}
The error it was throwing was " 'txt.val().length' is null or not an object". Can anyone help me on this.
thanks
var txt = $('#TextBox1');
This must go inside the function that's in the $()
call. Else you're trying to select the textbox before the DOM is ready.
Since your <script>
block is in the <head>
tag, it's executing before the document is parsed.
Therefore, when you write txt = $('#TextBox1')
, the textbox doesn't actually exist yet.
To fix this, you need to set the txt
variable after the document loads (inside #(function() { ... })
.
For example:
var txt;
$(function() {
txt = $('#TextBox1');
EnableDisableButtons();
txt.keyup(function() {
EnableDisableButtons();
});
});
TextBox1
looks like an ASP.Net server-side control.
If so, you should replace it with $('<%= TextBox1.ClientID %>
), since ASP.Net assigns its own unique IDs to server-side controls. Alternatively, in ASP.Net 4.0, you can add
ClientIDMode="Static"` to the textbox.
Also, you should give your textbox a meaningful name.
When var txt = $('#TextBox1');
is executed, the element does not exist yet (the DOM is not loaded completely).
Do:
var txt;
$(function() {
text = $('#TextBox1');
EnableDisableButtons();
txt.keyup(function() {
EnableDisableButtons();
});
});
or put the script at the end of you HTML document.
The function that is passed to $()
gets executed when the DOM is loaded, i.e. all the elements exist. Actually the purpose of this is that you can be sure that all the elements you might access are there.
精彩评论