input
input

Reputation: 7519

Variable declaration issue

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();

            });
        });

Upvotes: -1

Views: 261

Answers (3)

Kamil Lach
Kamil Lach

Reputation: 4629

You can also create global variable (I prefer warap it to class but won't do it this time to keep example simple):

var MyGlobal;

$("myTextBox").change(function(){
  MyGlobal = $(this).val();
});

Then your code should work so.. all looks like this:

   var bdmm;
    $(document).ready(function() {
            $("myTextBox").change(function(){
              bdmm = $(this).val();
            });

            $('#submit').click(function(e){
                    alert(bdmm);
            }); 
        });

Value is reinitialized when you edit textbox.

http://api.jquery.com/change/

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160191

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.

Upvotes: 4

Tadeck
Tadeck

Reputation: 137350

The problem is that probably just after the DOM is ready, your $("#bdmm").val() is empty, and when user tries to submit the form it already has some value.

So, outside the callback the field is empty, inside the callback the field has already been filled in.

Plus, I suggest using jQuery's .submit() function to bind to form submit instead of binding to form element's click event (unless the element with ID "submit" is different than form's submit button). This should give you more flexibility and should work also when the form is submitted by hitting "enter" button.

Upvotes: 1

Related Questions