I’ve a form in which I want to retrieve the value in the textbox using jQuery. The problem is if I declare the variable like this:
var bdmm = $("#bdmm").val();
in document.ready event but outside a function, and reference it in a function, the text value is null. However if I declare it inside the function, it works fine. Why is this so?
JQUERY:
This will NOT work:
$(document).ready(function() {
var bdmm = $("#bdmm").val();
$('#submit').click(function(e){
alert(bdmm);
e.preventDefault();
});
});
This will work:
$(document).ready(function() {
$('#submit').click(function(e){
alert($("#bdmm").val());
e.preventDefault();
//OR
var bdmm = $("#bdmm").val();
alert(bdmm);
e.preventDefault();
});
});
In the first example it retrieves the text box value immediately on DOM ready. If there’s already a value in it, it will work–but it won’t re-query the form when the click event actually occurs. Probably not what you want.
In the second example the form field value is retrieved when the click event actually occurs, which is almost certainly what you intend.