Paul's Programming Notes     Archive     Feed     Github

Jquery Add/Remove Class

Problem: In Jquery Mobile, I used the mobile.changePage (method) to switch pages. Now the button for the previous page is still blue.

Solution: Add Id's to the list items you'll be dealing with. Then use Jquery to remove the class "ui-btn-active" from the old button, and add the "ui-btn-active" class to the new button.

Here's the code:
$('#listItem1').removeClass('ui-btn-active')
$('#listItem2').addClass('ui-btn-active')

Global Variables In Javascript

Problem: I had two different <script> (javascript) sections, and I was unable to pass a variable from one set of <script> tags to the other.

Turns out it doesn't have anything to do with the script tags, and I just needed to learn a bit more about scope in Javascript. Apparently global variables are a common thing (maybe still not a good practice?) and as long as a variable is used outside of a function.. You'll be able to access the variable anywhere on the page.

Solution: Take the variable outside of the function.

Jquery Serialize

I spent a while looking for a good way to pass variables from HTML to Javascript (ajax) to PHP. Turns out Jquery’s serialize function is exactly what I needed.

Here’s an example of the code:

//this will send all the inputs in the form to php with ajax
$('#form').submit( function() {
     var data = form.$('input').serialize();
     $.ajax({
          type: "POST",
          url: "process.php",
          data: data,
          success: function(msg){
          alert( "Your quote request has been submitted!" );
          }
     });
     return false;
} );

http://api.jquery.com/serialize/

Also, you can use serializeArray() to get the data in a better format. Here’s a picture of the console.log output: