0

I have 8 search filters user can choose. When user clicks on filter it opens options for this filter. When user clicks out, the function hideFilterSearch() is triggered. I have problem about understanding of scope for variable formData (see below).

$(document).ready(function() {
    var formData = $("form").serialize();
});

function hideFilterSearch() {
    console.log(formData);
    $(".filters").hide();
    newFormData = $("form").serialize();
    if (formData != newFormData) {
        //newFormData is sent with ajax and search results are updates
    }
    formData = $("form").serialize();  
}

//show, hide filter changer
$('body').click(function(event) {
    if (!$(event.target).closest('.filter').length) {        
        hideFilterChanger();
    };
});

Console log gives me empty string in this case. I tried also to send formData as argument ()hideFilterSearch(formData), but then the problem is formData won't be updated. I am not sure what is the correct way to pass formData to function, but still update it's value inside function when it is changed.

2 Answers 2

1

Use global variable.As formData variable in local scope,you can't accesss it in antother function.

Change your code to the following

window.formData = $("form").serialize();
Sign up to request clarification or add additional context in comments.

Comments

0

Functions can return values. Pass formData and return the updated one from the function. You can then assign it in hideFilterChanged.

$(document).ready(function(){
 var formData = $("form").serialize();

 function hideFilterSearch(formData){
     console.log(formData);
     $(".filters").hide();
     newFormData = $("form").serialize();
     if(formData!=newFormData){
       //newFormData is sent with ajax and search results are updates
     }
     return $("form").serialize();  
   }

   //show, hide filter changer
   $('body').click(function(event) {
     if (!$(event.target).closest('.filter').length) {        
         formData = hideFilterChanger(formData);
     };
   });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.