jQuery: Name a generic function so I can call it after ajax event

I have the following code which sets up some custom form elements on the page load and then updates them if the user clicks on them:

// Setup Function
$(function () {
    $('form.vote_ballot > input:checked').prev().addClass('selected');
});

// Interaction Function
$(document).ready(function() {
    $('form.vote_ballot > label').click(function() {
        $(this).siblings().removeClass("selected").end()
            .addClass("selected");
    });
    $('form.vote_ballot').change(function() {
        $('form.vote_ballot').submit();
    });
});

This basically allows a user to give a "thumbs-up" or "thumbs-down" vote. The code works as expected when a user is editing an existing vote, but when they create a new vote an ajax request is processed and the initial setup function needs to be called again. The setup function should only be called once (which is why it's outside the document.ready block). The interaction portion in the document.ready block works fine before and after the ajax event.

I'm not very skilled with jQuery, and I haven't been able to figure out how to take the setup function and give it a name so I can call it again after the ajax event.

Any help?

Answers


This code:

$(function () {

and this:

$(document).ready(function() {

do exactly the same. So you can process everything on one block, like this:

$(function () {
    var setupFunction = function() {
      $('form.vote_ballot > input:checked').prev().addClass('selected');
    }

    // Setup Function
    setupFunction();

    // Interaction Function
    $('form.vote_ballot > label').click(function() {
        $(this).siblings().removeClass("selected").end()
            .addClass("selected");
    });
    $('form.vote_ballot').change(function() {
        $('form.vote_ballot').submit();
    });

    // example ajax call:
    $.ajax({ ...
      success: function () {
        ...
        addSelected(); // call from here for example
        ...
      }
    });
});

As you see I wrapped some part of code to a function (I called it setupFunction), and I can call it anywhere inside $(function () { ... }); block


Need Your Help

Capture hotkey in Swing

java swing hotkeys

I want to catch some hotkeys with 2 letter keys like Ctrl+P,P (Ctrl+P and press P without releasing Ctrl) but code below doesn't work:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.